linux端:
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #define MYPORT 3333
- #define BACKLOG 10
- main()
- {
- int sockfd, new_fd;
- struct sockaddr_in my_addr;
- struct sockaddr_in their_addr;
- int sin_size;
- if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
- perror("socket");
- exit(1);
- }
- my_addr.sin_family = AF_INET;
- my_addr.sin_port = htons(MYPORT);
- my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
- bzero(&(my_addr.sin_zero),0);
- if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr))== -1) {
- perror("bind");
- exit(1);
- }
- if (listen(sockfd, BACKLOG) == -1) {
- perror("listen");
- exit(1);
- }
- while(1) {
- sin_size = sizeof(struct sockaddr_in);
- if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr,&sin_size)) == -1) {
- perror("accept");
- continue;
- }
- printf("server: got connection from %s\n",inet_ntoa(their_addr.sin_addr));
- if (!fork()) {
- if (send(new_fd, "Hello, world!\n", 14, 0) == -1)
- perror("send");
- close(new_fd);
- exit(0);
- }
- close(new_fd);
- while(waitpid(-1,NULL,WNOHANG) > 0);
- }
- }
window端:
- // client.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include
- //#include
- //#include
- #include
- #pragma comment (lib,"WS2_32.lib")
- #include
- //using namespace std;
- int _tmain(int argc, _TCHAR* argv[])
- {
- int i;
- char recvBuffer[255];
- WORD wVersionRequested; //typedef unsigned short WORD; 2字节
- WSADATA wsaData;
- //WSADATA 包含了Windows Socket执行的信息。
- int err;
- wsaData.wVersion =MAKEWORD(1,1);
- //这个宏创建一个被指定变量连接而成的WORD变量。返回一个WORD变量。
- //第一个是socket库版本,第二个是取得的版本号。
- err=WSAStartup(wVersionRequested,&wsaData); //return 0 if successful
- if(err!=0){
- printf("Call WSAStart ERROR!");
- exit(1);
- } //终止对WinSock库的使用
- //if(LOBYTE(wsaData.wVersion)!=1|| HIBYTE(wsaData.wHighVersion)!=1)
- //{
- // WSACleanup();
- // exit(0);
- //}
- //typedef unsigined int SOCKET;//创建用与监听的套接字
- SOCKET SocketClient=socket(AF_INET,SOCK_STREAM,0); //0表示让系统自己选择协议
- //定义地址结构体//填入服务器端的ip地址和端口号
- SOCKADDR_IN addrSrv;
- //转换为TCP/IP network byte order //32bit
- addrSrv.sin_addr.S_un.S_addr=inet_addr("172.17.51.81"); //ip 172.17.51.81
- addrSrv.sin_family=AF_INET; //family address
- addrSrv.sin_port=htons(3333); //16bit端口号
- printf("Connect to server...\n");
- i=connect(SocketClient,(sockaddr *)&addrSrv,sizeof(SOCKADDR_IN)); //指向要建立连接的数据结构
- if(i
- printf("%i\n",WSAGetLastError());
- printf("连接到172.17.51.81:3333错误!");
- exit(1);
- }
- recv(SocketClient,recvBuffer,255,0);
- printf("%s\n",recvBuffer); //send(socketClient,recvBuffer,20,0);
- closesocket(SocketClient);
- WSACleanup();
- return 0;
- }
- 注:
1、windows下控制台程序,需要注意加链接库ws2_32.lib
2、文件名以cpp结尾,解决SOCKET等符号找不到问题
3、#include 解决exit符号找不到问题
4、补充第1点:#pragma comment (lib,"WS2_32.lib")