gpt4 book ai didi

sockets - 我无法在此代码中连接udp服务器和udp客户端?

转载 作者:行者123 更新时间:2023-12-03 11:57:26 26 4
gpt4 key购买 nike

UDP_SERVER

int main()
{
int sockfd,clilen;
char arr[20];
struct sockaddr_in serv_add,cliaddr;


if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0)
printf("error");
bzero((char *)&serv_add,sizeof(serv_add));
serv_add.sin_family=AF_INET;
serv_add.sin_port=htons(6060);
serv_add.sin_addr.s_addr=inet_addr("127.0.0.1");


if(bind(sockfd,(struct sockaddr *)&serv_add,sizeof(serv_add))<0)
printf("bind error");

//while(1)
{

//recv(sockfd,&arr,10,0);
clilen=sizeof(cliaddr);
recvfrom(sockfd,arr,10,0,(struct sockaddr *)&cliaddr,&clilen);
printf("%s",arr);
}
close(sockfd);
return 0;
}

UDP_CLIENT
int main()
{
int sockfd;
struct sockaddr_in servaddr,cliaddr;

sockfd=socket(AF_INET,SOCK_DGRAM,0);

bzero((char *)&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=6060;
servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");

bzero((char *)&cliaddr,sizeof(cliaddr));
cliaddr.sin_family=AF_INET;
cliaddr.sin_port=htons(0);
cliaddr.sin_addr.s_addr=htonl(INADDR_ANY);
//printf("%s")

if(bind(sockfd,(struct sockaddr *)&cliaddr,sizeof(cliaddr))<0)
printf("error");

sendto(sockfd,"subh.singh",10,0,(struct sockaddr *)&servaddr,sizeof(servaddr));
close(sockfd);
return 0;
}

最佳答案

在客户端,您忘记了htons:

servaddr.sin_port=6060; /* Wrong. */
servaddr.sin_port = htons(6060); /* Right. */

关于sockets - 我无法在此代码中连接udp服务器和udp客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6999355/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com