gpt4 book ai didi

c - UDP 套接字编程——recvfrom() 一个端口和 sendto() 另一个端口

转载 作者:行者123 更新时间:2023-11-30 19:32:02 26 4
gpt4 key购买 nike

UDP Socket 编程 - 服务器监听端口 5000 - 客户端监听端口 6000来自一个端口的 recvfrom() - 5000
sendto() 到其他端口 - 6000 到同一客户端。

服务器.c

#include <stdio.h>          /* for printf() and fprintf() */
#include <sys/socket.h> /* for socket() and bind() */
#include <arpa/inet.h> /* for sockaddr_in and inet_ntoa() */
#include <stdlib.h> /* for atoi() */
#include <string.h> /* for memset() */
#include <unistd.h> /* for close() */

#define MAXSIZE 255 /* Longest string */
#define SRC_PORT 5000
#define DST_PORT 6000

int main(int argc, char *argv[])
{
int sock; /* Socket */
struct sockaddr_in ServAddr; /* Local address */
struct sockaddr_in ClntAddr; /* Client address */
socklen_t CliAddrLen; /* Length of incoming message */
char recBuffer[MAXSIZE]; /* Buffer for echo string */
int recvMsgSize; /* Size of received message */
int i;

/* Create socket for sending/receiving datagrams */
if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
DieWithError("socket() failed");

/* Construct local address structure */
memset(&ServAddr, 0, sizeof(ServAddr)); /* Zero out structure */
ServAddr.sin_family = AF_INET; /* Internet address family */
ServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
ServAddr.sin_port = htons(SRC_PORT); /* Local port */

/* Construct address structure */
memset(&ClntAddr, 0, sizeof(ClntAddr)); /* Zero out structure */
ClntAddr.sin_family = AF_INET; /* Internet address family */
ClntAddr.sin_addr.s_addr = inet_addr("192.168.1.*");
ClntAddr.sin_port = htons(DST_PORT);


/* Bind to the local address */
if (bind(sock, (struct sockaddr *) &ServAddr, sizeof(ServAddr)) < 0)
DieWithError("bind() failed");

for (;;) /* Run forever */
{
printf("Listening on UDP:5000 \n");
/* Set the size of the in-out parameter */
cliAddrLen = sizeof(ClntAddr);

/* Block until receive message from a client */
if ((recvMsgSize = recvfrom(sock, recBuffer, MAXSIZE, 0,(struct sockaddr *) &ClntAddr, &cliAddrLen)) < 0)
DieWithError("recvfrom() failed") ;

printf("Handling Client: %s\n", inet_ntoa(ClntAddr.sin_addr));



printf("Received Data: %s",recBuffer);
printf("\n");

/* Send response datagram back to the client */


if (sendto(sock, recBuffer, MAXSIZE, 0, (struct sockaddr *) & ClntAddr, sizeof(ClntAddr)) < 0)
DieWithError("sendto() failed");

}
/* NOT REACHED */
}

它工作得很好。客户端和服务器编程使用不同的端口来发送和接收数据。谢谢问候

最佳答案

这是错误的

lntAddr.sin_addr.s_addr = inet_addr("CLIENT_IP"); 

inet_addr 采用点分 IP 地址而不是主机名

关于c - UDP 套接字编程——recvfrom() 一个端口和 sendto() 另一个端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47533407/

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