//服務端
#include
#include
#include
#include
#include
#include
#define maxline 80
#define serv_port 502
void do_echo(int sockfd, struct sockaddr *pcliaddr, socklen_t clilen)
}int main(void)
printf("upd servese is bind success and do_echo now\n");
do_echo(sockfd, (struct sockaddr *)&cliaddr, sizeof(cliaddr));
return 0;
}//客戶端1 使用本地固定的埠
#include
#include
#include
#include
#include
#include
#include
#include
#define maxline 80
#define serv_port 8888
void do_cli(file *fp, int sockfd, struct sockaddr *pservaddr, socklen_t servlen)
printf("please input your str want to send:\n");
while(fgets(sendline, maxline, fp) != null)
recvline[n] = 0; /* terminate string */
printf("receive str:\n");
fputs(recvline, stdout);
printf("\n******************************====\n");
printf("please input your str want to send:\n");}}
int main(int argc, char **argv)
/* init servaddr */
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = af_inet;
servaddr.sin_port = htons(serv_port);
if(inet_pton(af_inet, argv[1], &servaddr.sin_addr) <= 0)
sockfd = socket(af_inet, sock_dgram, 0);
printf("cli is ready,now do funtion do_cli! \n", argv[1]);
do_cli(stdin, sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
return 0;
}//客戶端2 ** 使用隨機埠
//#include
#include
#include
#include
#include
#include
#include
#include
#define serv_port 502
#define maxline 80
void do_cli(file *fp, int sockfd, sockaddr_in toaddr)
printf("wait for data ...\n");
/* receive data from server */
//n = read(sockfd, recvline, maxline);
unsigned int fromlen = sizeof(fromaddr);
if(recvfrom(sockfd,recvline,maxline,0,
(struct sockaddr*)&fromaddr,&fromlen)<0)
else
recvline[strlen(sendline)-1] = 0;
printf("receive str:\n");
fputs(recvline, stdout);
printf("\n******************************====\n");
printf("please input your str want to send:\n");}}
int main(int argc, char *argv)
memset(&toaddr,0,sizeof(toaddr));
toaddr.sin_family=af_inet;
toaddr.sin_addr.s_addr=inet_addr("192.168.0.110");
toaddr.sin_port = htons(serv_port);
do_cli(stdin, sock, toaddr);
close(sock);
return 0;
}
Linux下的UDP通訊
日期 2012 06 02 字型 大中小 今天我們介紹如何編寫linux下的udp程式,關於tcp程式可以參考這裡 由於udp通訊不需要事先建立連線,因此不需要tcp中的connect函式。伺服器端的步驟如下 1.socket 建立乙個socket 2.bind 將這個socket繫結在某個埠上 a...
C 簡單的UDP通訊例子
1 1,udp客戶端23 using system 4using system.collections.generic 5using system.componentmodel 6using system.data 7using system.drawing 8using system.linq 9...
linux下C 實現UDP通訊
簡要介紹udp原理,通過 例項講解。本篇部落格不強調server跟client 的概念,重在實現雙方互通。收的一方 socket bind recvfrom close 發的一方 socket sendto close 只有收資料的一方需要bind 而傳送的一方不需要bind 由上圖可以看出,bin...