一個linux UDP網路通訊的例子原始碼(server、client方式)

來源:互聯網
上載者:User
一個linux UDP網路通訊的例子原始碼(server、client方式)

伺服器端代碼#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>int main(int argc, char *argv[])
{
int sock;
//sendto中使用的對方地址
struct sockaddr_in toAddr;
//在recvfrom中使用的對方主機地址
struct sockaddr_in fromAddr;int recvLen;
unsigned int addrLen;
char recvBuffer[128];sock = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);if(sock < 0)
{
 printf("建立通訊端失敗了./r/n");
 exit(0);
}memset(&fromAddr,0,sizeof(fromAddr));
fromAddr.sin_family=AF_INET;
fromAddr.sin_addr.s_addr=htonl(INADDR_ANY);
fromAddr.sin_port = htons(4000);if(bind(sock,(struct sockaddr*)&fromAddr,sizeof(fromAddr))<0)
{
 printf("bind() 函數使用失敗了./r/n");
 close(sock);
 exit(1);
}while(1){
addrLen = sizeof(toAddr);
if((recvLen = recvfrom(sock,recvBuffer,128,0,(struct sockaddr*)&toAddr,&addrLen))<0)
{
 printf("()recvfrom()函數使用失敗了./r/n");
 close(sock);
 exit(1);
}
if(sendto(sock,recvBuffer,recvLen,0,(struct sockaddr*)&toAddr,sizeof(toAddr))!=recvLen){
printf("sendto fail/r/n");
close(sock);
exit(0);
}
return 0;
}
}

用戶端代碼
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>int main(int argc, char *argv[])
{
if(argc < 2)
{
 printf("請輸入要傳送的內容./r/n");
 exit(0);
}
int sock;
//sendto中使用的對方地址
struct sockaddr_in toAddr;
//在recvfrom中使用的對方主機地址
struct sockaddr_in fromAddr;unsigned int fromLen;
char recvBuffer[128];
sock = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);if(sock < 0)
{
 printf("建立通訊端失敗了./r/n");
 exit(1);
}memset(&toAddr,0,sizeof(toAddr));
toAddr.sin_family=AF_INET;
toAddr.sin_addr.s_addr=inet_addr("127.0.0.1");
toAddr.sin_port = htons(4000);if(sendto(sock,argv[1],strlen(argv[1]),0,(struct sockaddr*)&toAddr,sizeof(toAddr)) != strlen(argv[1]))
{
 printf("sendto() 函數使用失敗了./r/n");
 close(sock);
 exit(1);
}fromLen = sizeof(fromAddr);
if(recvfrom(sock,recvBuffer,128,0,(struct sockaddr*)&fromAddr,&fromLen)<0)
{
 printf("()recvfrom()函數使用失敗了./r/n");
 close(sock);
 exit(1);
}
printf("recvfrom() result:%s/r/n",recvBuffer);
close(sock);} 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.