如何在c中设置UDP套接字中的源端口?
Posted
技术标签:
【中文标题】如何在c中设置UDP套接字中的源端口?【英文标题】:How to set the source port in the UDP socket in c? 【发布时间】:2012-04-10 00:16:59 【问题描述】:谁能告诉我如何在 UDP 套接字中设置源端口地址?我的客户端应用程序需要将数据包从 57002 端口发送到服务器端口 58007 。
【问题讨论】:
【参考方案1】:#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define DST_PORT 58007
#define SRC_PORT 57002
#define IP "127.0.0.1"
int main(int argc, char *argv[])
struct sockaddr_in addr, srcaddr;
int fd;
char message[] = "Hello, World!";
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
perror("socket");
exit(1);
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(IP);
addr.sin_port = htons(DST_PORT);
memset(&srcaddr, 0, sizeof(srcaddr));
srcaddr.sin_family = AF_INET;
srcaddr.sin_addr.s_addr = htonl(INADDR_ANY);
srcaddr.sin_port = htons(SRC_PORT);
if (bind(fd, (struct sockaddr *) &srcaddr, sizeof(srcaddr)) < 0)
perror("bind");
exit(1);
while (1)
if (sendto(fd, message, sizeof(message), 0, (struct sockaddr *) &addr,
sizeof(addr)) < 0)
perror("sendto");
exit(1);
sleep(1);
return 0;
【讨论】:
如果源端口未绑定,如何选择随机源端口以及范围可以以某种方式控制/指定?【参考方案2】:bind(2)
它。使用INADDR_ANY
地址和您的端口号。
【讨论】:
链接的手册页有一个示例。这是另一个alas.matf.bg.ac.rs/manuals/lspe/snode=47.html【参考方案3】:struct sockaddr_in servaddr,cliaddr;
sockfd=socket(AF_INET,SOCK_DGRAM,0);
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr=inet_addr(argv[1]);
servaddr.sin_port=htons(32000); //destination port for incoming packets
cliaddr.sin_family = AF_INET;
cliaddr.sin_addr.s_addr= htonl(INADDR_ANY);
cliaddr.sin_port=htons(33000); //source port for outgoing packets
bind(sockfd,(struct sockaddr *)&cliaddr,sizeof(cliaddr));
use sendto with servaddr
use recvfrom with cliaddr
if u check wireshark u will see source port as 33000 and destination port as 32000 for sendto operation
【讨论】:
【参考方案4】: struct sockaddr_in sa;
int ret, fd;
memset(&sa, 0, sizeof(struct sockaddr_in));
sa.sin_family = AF_INET;
sa.sin_port = htons(LOCAL_PORT);
sa.sin_addr.s_addr = inet_addr(LOCAL_IP_ADDRESS);
ret = bind(fd, (struct sockaddr *)&sa, sizeof(struct sockaddr));
【讨论】:
以上是关于如何在c中设置UDP套接字中的源端口?的主要内容,如果未能解决你的问题,请参考以下文章