在winsock中,应用程序通过Sockaddr_in 结构来指定IP地址和服务端口信息:
sockaddr_in internetAddr;
int nPortID = 5320;
internetAddr.sin_family = AF_INET;
internetAddr.sin_addr.s_addr = inet_addr(“202.202.42.88”);
internetAddr.sin_port = htons(nPortID);
ip地址不容易记忆,还提供了许多地址和名称解析函数如gethostbyname,gethostbyaddr等
=======客户端======
#include <stdio.h> #include <winsock2.h> #pragma comment (lib,"WS2_32") int main(int argc, char* argv[]) { SOCKET sock; struct sockaddr_in sa; int err; int servport = 5555; char buff[256]; int len; WSADATA ws; //初始化WinSock if(WSAStartup(0x0101,&ws) != 0) { printf("WSAStartup() failed!\n"); exit(-1); } //创建套接字 sock =socket(AF_INET,SOCK_STREAM,0); //定义服务器地址结构 memset(&sa,0,sizeof(sa)); sa.sin_family = AF_INET; sa.sin_port = htons(servport); sa.sin_addr.s_addr=inet_addr("127.0.0.1") ; //链接服务器 err=connect(sock,(const sockaddr*)&sa,sizeof(sa)); //接收欢迎词 memset(buff,0,sizeof(buff)); len =recv(sock,buff,sizeof(buff),0); printf("%s\n",buff); closesocket(sock); WSACleanup(); return 0; }
=======服务器=======
#include <stdio.h> #include <winsock2.h> #pragma comment (lib,"WS2_32") int main(int argc, char* argv[]) { SOCKET servsock,clisock; struct sockaddr_in sa; struct sockaddr_in cliaddr; int servport = 5555; char buff[256]; WSADATA ws; int len,err; //初始化Winsock if(WSAStartup(0X0101,&ws) != 0) { printf("WSAStartup() failed!\n"); exit(-1); } //创建套接字 printf("Create Socket...\n"); servsock = socket(AF_INET,SOCK_STREAM,0); //填充服务器地址结构 memset(&sa,0,sizeof(sa)); sa.sin_family = AF_INET; sa.sin_port=htons(servport); sa.sin_addr.s_addr = inet_addr("127.0.0.1"); //绑定套接字到服务器地址结构 printf("Binding...\n"); err = bind(servsock,(const sockaddr*)&sa,sizeof(sa)); if(err != 0) { fprintf(stderr,"Bind failed:%d\n",WSAGetLastError()); exit(-2); } //监听套接字 printf("Listeing...\n"); err = listen(servsock,5); if(err != 0) { fprintf(stderr,"Listen failed:%d\n",WSAGetLastError()); exit(-3); } //等待连接请求 printf("Waiting Request...\n"); len = sizeof(cliaddr); clisock =accept(servsock,(struct sockaddr*)&cliaddr,&len); printf("Accept Client:%s:%d",inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port)); sprintf(buff,"Welcome %s",inet_ntoa(cliaddr.sin_addr)); send(clisock,buff,strlen(buff),0); closesocket(clisock); WSACleanup(); return 0; }