Linux Socket程式設計 例項

2021-08-25 15:03:43 字數 2303 閱讀 9933

tcp協議:

伺服器端:tcp_server.c

#include #include #include #include #include int main(int argc, char *argv)      /*將套接字繫結到伺服器的網路位址上*/   if (bind(s,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))<0)      /*監聽連線請求--監聽佇列長度為5*/   listen(s,5);   sin_size=sizeof(struct sockaddr_in);   /*等待客戶端連線請求到達*/   if((fd=accept(s,(struct sockaddr *)&remote_addr,&sin_size))<0)      printf("accept client %s/n",inet_ntoa(remote_addr.sin_addr));   len=send(fd,"welcome to my server/n",21,0);//傳送歡迎資訊   /*接收客戶端的資料並將其傳送給客戶端--recv返回接收到的位元組數,sand返回傳送的位元組數*/   while((len=recv(fd,buf,bufsiz,0))>0))      }   close(fd);   close(s);   return 0;   }

客戶端:tcp_client.c

#include #include #include #include #include int main(int argc, char *argv)      /*將套接字繫結到伺服器的網路位址上*/   if (connect(s,(struct sockaddr *)&remote_addr,sizeof(struct sockaddr))<0)    printf("connected to server/n");   len=recv(s,buf,bufsiz,0);//接收伺服器端資訊   buf[len]='/0';   printf("%s",buf); //列印伺服器端資訊   /*迴圈的傳送接收資訊並列印接收資訊--recv返回接收到的位元組數,sand返回傳送的位元組數*/   while(1)      len=send(s,buf,strlen(buf),0);   len=recv(s,buf,bufsiz,0);   buf[len]='/0';   printf("received:%s/n",buf);   }   close(s);//關閉套接字   return 0;   }   udp協議:   伺服器端:udp_server.c   #include #include #include #include #include int main(int argc, char *argv)      /*將套接字繫結到伺服器的網路位址上*/   if (bind(s,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))<0)      sin_size=sizeof(struct sockaddr_in);   printf("waiting for a packet.../n");   /*接收客戶端的資料並將其傳送給客戶端--recvfrom是無連線的*/   if((len=recvfrom(s,buf,bufsiz,0,(struct sockaddr *)&remote_addr,&sin_size))<0)      printf("received packet from %s:/n",inet_ntoa(remote_addr.sin_addr));   buf[len]='/0';   printf("contents: %s/n",buf);   close(s);   return 0;   }

客戶端:udp_client.c

#include #include #include #include #include int main(int argc, char *argv)      strcpy(buf,"this is a test message");   printf("sending: '%s'/n",buf);   sin_size=sizeof(struct sockaddr_in);   /*向伺服器傳送資料報*/   if((len=sendto(s,buf,strlen(buf),0,(struct sockaddr *)&remote_addr,sizeof(struct sockaddr)))<0)      close(s);   return 0;   }   

socket函式api.cpp

htons();//將short型別的值從主機位元組序轉換為網路位元組序

inet_addr();//將ip位址字串轉換為long型別的網路位元組序

gethostbyname();//獲得與該網域名稱對應的ip位址

inet_ntoa();//將long型別的網路位元組序轉換成ip位址字串

Linux Socket程式設計 例項

tcp協議 伺服器端 tcp server.c include include include include include int main int argc,char argv 將套接字繫結到伺服器的網路位址上 if bind s,struct sockaddr my addr,sizeof ...

Linux Socket程式設計簡單例項

include include include include include include includechar host name 127.0.0.1 int port 7778 struct student t int main if connect socket descriptor,v...

linux socket 程式設計

兩段程式 可用於開發板和主機之間的資料傳輸,很管用!file client.c檔案傳輸客戶端程式示例 本檔案是客戶機的 include for sockaddr in include for socket include for socket include for printf include f...