服務端說明 #include <errno.h> //一些錯誤資訊的處理#include <stdio.h> // 標準輸入輸出#include <sys/types.h> //基本系統資料類型#include <netinet/in.h> //Internet address family 定義像sockaddr_in這個的地址族#include <sys/socket.h> //socket #include <unistd.h> //系統定義符號常量的標頭檔,包含了許多UNIX系統服務的函數原型,例如read函數、write函數#include <netdb.h> //netdb.h 定義了與網路有關的結構,變數類型,宏,函數。如:struct hostent *gethostbyaddr(const void *addr, size_t len, int type);#include <arpa/inet.h> // 定義了 inet_addr#include <fcntl.h> //fcntl.h定義了很多宏和open,fcntl函數原型 close等#include <stdlib.h> //標準庫#include <string.h> //stringint main(int argc, const char * argv[]){ int sfp,nfp; //通訊端描述符 struct sockaddr_in s_add,c_add; //服務端和用戶端地址 unsigned int sin_size; unsigned short portnum=3000; //綁定連接埠號碼 printf("Hello,welcome to my server !\r\n"); sfp = socket(AF_INET, SOCK_STREAM, 0); //通訊端描述符 if(-1 == sfp)//如果失敗 { printf("socket fail ! \r\n"); return -1; } printf("socket ok !\r\n"); bzero(&s_add,sizeof(struct sockaddr_in));//清0 s_add.sin_family=AF_INET; s_add.sin_addr.s_addr=htonl(INADDR_ANY);// 任何地址 s_add.sin_port=htons(portnum);//連接埠號碼 if(-1 == bind(sfp,(struct sockaddr *)(&s_add), sizeof(struct sockaddr))) //如果綁定失敗 { printf("bind fail !\r\n"); return -1; } printf("bind ok !\r\n"); if(-1 == listen(sfp,5))//如果listen失敗 { printf("listen fail !\r\n"); return -1; } printf("listen ok\r\n"); while(1) { sin_size = sizeof(struct sockaddr_in); nfp = accept(sfp, (struct sockaddr *)(&c_add), &sin_size);//不斷accept //如果accpet成功的話,用戶端的一些資訊就在 c_add 中 if(-1 == nfp)//失敗 { printf("accept fail !\r\n"); return -1; } printf("accept ok!\r\nServer start get connect from %#x : %#x\r\n", ntohl(c_add.sin_addr.s_addr),ntohs(c_add.sin_port)); // 列印用戶端的地址和連接埠 if(-1 == write(nfp,"hello,welcome to my server \r\n",32))//寫入資料 { printf("write fail!\r\n"); return -1; } printf("write ok!\r\n"); close(nfp);//關閉 } close(sfp);//關閉 return 0;} 用戶端說明 #include <errno.h>#include <stdio.h>#include <sys/types.h>#include <netinet/in.h>#include <sys/socket.h>#include <unistd.h>#include <netdb.h>#include <arpa/inet.h>#include <fcntl.h>#include <stdlib.h>#include <string.h> int main(){ int cfd;//通訊端描述符 ssize_t recbytes;//接受位元組長度 char buffer[1024]={0};//接收位元組緩衝區 struct sockaddr_in s_add;//串連的地址 unsigned short portnum=3000;//串連連接埠 printf("Hello,welcome to client !\r\n"); cfd = socket(AF_INET, SOCK_STREAM, 0); if(-1 == cfd) { printf("socket fail ! \r\n"); return -1; } printf("socket ok !\r\n"); bzero(&s_add,sizeof(struct sockaddr_in));//清空 s_add.sin_family=AF_INET; s_add.sin_addr.s_addr= inet_addr("192.168.1.101"); s_add.sin_port=htons(portnum); printf("s_addr = %#x ,port : %#x\r\n",s_add.sin_addr.s_addr,s_add.sin_port); if(-1 == connect(cfd,(struct sockaddr *)(&s_add), sizeof(struct sockaddr)))//開始串連 { printf("connect fail !\r\n"); return -1; } printf("connect ok !\r\n"); ssize_t num=1024; if(-1 == (recbytes = read(cfd,buffer,num)))//如果讀取失敗 { printf("read data fail !\r\n"); return -1; } printf("read ok\r\nREC:\r\n"); buffer[recbytes]='\0'; printf("%s\r\n",buffer); getchar(); close(cfd); return 0;}