在windows下使用winsock2.h
库的时候出现下面的问题:
net.cpp:(.text+0x2f): undefined reference to `__imp_WSAStartup'
net.cpp:(.text+0x48): undefined reference to `__imp_socket'
net.cpp:(.text+0x93): undefined reference to `__imp_inet_addr'
net.cpp:(.text+0xaa): undefined reference to `__imp_htons'
net.cpp:(.text+0xcc): undefined reference to `__imp_bind'
net.cpp:(.text+0x120): undefined reference to `__imp_listen'
net.cpp:(.text+0x189): undefined reference to `__imp_inet_ntoa'
net.cpp:(.text+0x1c9): undefined reference to `__imp_accept'
net.cpp:(.text+0x1f3): undefined reference to `__imp_inet_ntoa'
net.cpp:(.text+0x221): undefined reference to `__imp_closesocket'
解决方式是编译的时候设置-lwsock32
参数,比如:
g++ net.cpp -lwsock32 -o net
#include <iostream>
#include <WinSock2.h>
#include <signal.h>
using std::cout;
using std::endl;
// 注意编译的时候需要使用 -lwsock32 命令
const int PORT = 8080;
const int QUEUE_SIZE = 20;
int main(){
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(2,2);
WSAStartup(wVersionRequested, &wsaData);
int sd = socket(AF_INET, SOCK_STREAM, 0);
if (sd == -1){
cout << "create socket err"<<endl;
return -1;
}
sockaddr_in addr;
addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
int r = bind(sd, (sockaddr*)&addr, sizeof(addr));
if (r == -1){
cout << "bind socket err"<<endl;
return -1;
}
if (listen(sd, QUEUE_SIZE)==-1){
cout << "listen socket err"<<endl;
return -1;
}
cout << "INFO: "<<"listen on: " << inet_ntoa(addr.sin_addr)<<":"<<PORT<<endl;
while(true){
sockaddr_in addr;
int length = sizeof(addr);
int s = accept(sd, (sockaddr*)&addr, &length);
cout << "deal with socket: "<< inet_ntoa(addr.sin_addr)<<":"<<ntohs(addr.sin_port)<<endl;
closesocket(s);
}
WSACleanup();
return 0;
}