谁能给个C语言socket 通信,用UDP协议的代码例子。。

2024-12-02 14:02:36
推荐回答(2个)
回答1:

我的是包含的#include ,参考一下吧

#include
#include
#include
#include
#include
#include

int main(void)
{
int sfd; char buf[1024]; int n, i;
struct sockaddr_in serv_addr, cli_addr;
socklen_t len;

sfd = socket(AF_INET, SOCK_DGRAM, 0);

memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(8000);
inet_pton(AF_INET, "192.168.0.36", &serv_addr.sin_addr.s_addr);

while(1) {
if(fgets(buf, 1024, stdin) == NULL)
break;
sendto(sfd, buf, strlen(buf), 0, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
n = recvfrom(sfd, buf, 1024, 0, NULL, NULL);
write(STDOUT_FILENO, buf, n);
}
close(sfd);

return 0;
}


#include
#include
#include
#include
#include

int main(void)
{
int sfd; char buf[1024]; int n, i;
struct sockaddr_in serv_addr, cli_addr;
socklen_t len;

sfd = socket(AF_INET, SOCK_DGRAM, 0);

memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(8000);
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

bind(sfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));

while(1) {
len = sizeof(cli_addr);
n = recvfrom(sfd, buf, 1024, 0, (struct sockaddr *)&cli_addr, &len);
for(i = 0; i < n; i++)
buf[i] = toupper(buf[i]);
sendto(sfd, buf, n, 0, (struct sockaddr *)&cli_addr, len);
}
close(sfd);

return 0;
}
请求采纳,谢谢!

回答2:

#include

#include
#include
#include
#include
#include
#include

int main(void)
{
int sfd; char buf[1024]; int n, i;
struct sockaddr_in serv_addr, cli_addr;
socklen_t len;

sfd = socket(AF_INET, SOCK_DGRAM, 0);

memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(8000);
inet_pton(AF_INET, "192.168.0.36", &serv_addr.sin_addr.s_addr);

while(1) {
if(fgets(buf, 1024, stdin) == NULL)
break;
sendto(sfd, buf, strlen(buf), 0, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
n = recvfrom(sfd, buf, 1024, 0, NULL, NULL);
write(STDOUT_FILENO, buf, n);
}
close(sfd);

return 0;
}


#include
#include
#include
#include
#include

int main(void)
{
int sfd; char buf[1024]; int n, i;
struct sockaddr_in serv_addr, cli_addr;
socklen_t len;

sfd = socket(AF_INET, SOCK_DGRAM, 0);

memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(8000);
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

bind(sfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));

while(1) {
len = sizeof(cli_addr);
n = recvfrom(sfd, buf, 1024, 0, (struct sockaddr *)&cli_addr, &len);
for(i = 0; i < n; i++)
buf[i] = toupper(buf[i]);
sendto(sfd, buf, n, 0, (struct sockaddr *)&cli_addr, len);
}
close(sfd);

return 0;
}