套接字编程

时间:2017-04-13 14:34:10
【文件属性】:

文件名称:套接字编程

文件大小:2KB

文件格式:CPP

更新时间:2017-04-13 14:34:10

winsockt

#include #include #include #pragma comment(lib,"wsock32.lib") #define MAX_LEN 1024 //数据报格式 struct Mes_pack { char* ip_addr; char* data_buf; int data_len; }; struct Sock_data { SOCKET sock; SOCKADDR_IN addr; }; void InitListenSocket(SOCKET& Listen_Socket) { int ret; WSADATA wsadata; int Port = 5150; SOCKADDR_IN Server_Addr; if ((ret = WSAStartup(MAKEWORD(2,2), &wsadata)) != 0) { printf("WSAStartup failed with error %d\n", ret); return; } if ((Listen_Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) { printf("socket failed with error %d\n", WSAGetLastError()); WSACleanup(); return; } u_long iMode = 1; ioctlsocket(Listen_Socket, FIONBIO, &iMode);//通常socket运行后默认为阻塞模式。要调用ioctlsocket函数设置非阻塞模式。 Server_Addr.sin_family = AF_INET; Server_Addr.sin_port = htons(Port); //将16bit字符从host字节序转化成网络字节序 Server_Addr.sin_addr.s_addr = htonl(INADDR_ANY);//将32bit字符从host转化成网络的 if (bind(Listen_Socket, (SOCKADDR *)&Server_Addr, sizeof(Server_Addr))== SOCKET_ERROR) { printf("bind failed with error %d\n", WSAGetLastError()); closesocket(Listen_Socket); WSACleanup(); return; } if (listen(Listen_Socket, 5) == SOCKET_ERROR) { printf("listen failed with error %d\n", WSAGetLastError()); closesocket(Listen_Socket); WSACleanup(); return; } printf("We are awaiting a connection on port %d.\n", Port); }


网友评论