在linux中:
我正在编写代码来实现UDP套接字。
我想填写udp标头字段,因此我必须分配源和目标端口号。
例如:
struct udphdr *udph
//UDP header
udph->source = htons (6666);
udph->dest = htons (8622);
此外,我必须准备包含端口号字段的struct sockaddr_in,例如:
//internet socket structure
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(80);
sockaddr_in结构中的端口号值与UDP头中的端口号值之间是否有任何关系?
分配这些值的正确方法是什么?
这是我的完整代码:
#include <stdio.h>
#include <unistd.h> //sleep
//socket headers
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h> //when socket creation failed
//#include <netinet/tcp.h> //Provides declarations for tcp header
#include <netinet/udp.h> //Provides declarations for udp header
#include <netinet/ip.h> //Provides declarations for ip header
#include <stdlib.h> //for exit();
#include <string.h> //memset
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
//declarations
int sokt_fd;
//buffers
char datagram[80];// 80 bytes datagram
char *data;//buffer for payload
//code here
//Create a udp socket
if((sokt_fd=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) <0)
{
//socket creation failed, may be because of non-root privileges
perror("Failed to create socket");
exit(1);
}
//zero out the packet buffer
memset (datagram, 0, 80);
//UDP header
struct udphdr *udph = (struct udphdr *) datagram;//assign startof udp
//Data part
data = datagram + sizeof(struct udphdr);//assigin location of data
strcpy(data , "ABC");
//UDP header
udph->source = htons (6666);
udph->dest = htons (8622);
udph->len = htons(8 + strlen(data)); //UDP header size
//disable checksum
udph->check = 0; //leave checksum 0 now, filled later by pseudo header
//internet socket structure
//destination IP address, and port
//http://www.beej.us/guide/bgnet/output/html/singlepage/bgnet.html#sendtorecv
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(80);
sin.sin_addr.s_addr = inet_addr ("10.0.0.2"); //destenation IP address,
//sending the datagram:
while(1)
{
if (sendto (sokt_fd,datagram,udph->len,0/*int flags*/,(struct sockaddr *) &sin, sizeof (sin))<0)
{
perror("sendto failed");
}
else
{
printf ("Packet Send. Length : %d \n" , udph->len);
}
sleep(5);
}
return 0;
}
答案 0 :(得分:1)
如果你是一个IPPROTO_UDP套接字,你就不会搞乱udp头文件。
这是来自端口6666上将UDP发送到127.0.0.1的内容的片段。
struct in_addr in;
struct sockaddr_in sdest;
memset(&sdest, 0, sizeof(sdest));
sdest.sin_family = AF_INET;
sdest.sin_port = htons(6666);
inet_aton("127.0.0.1", &in);
sdest.sin_addr.s_addr = in.s_addr;
r = sendto(sock, data, size, 0, (struct sockaddr *) &sdest, (socklen_t) sizeof(sdest));
但你也应该看看bind
。这允许你接收东西(总是有用的),但主要是你应该看看W Richard Stevens等人{0}中的优秀例子,ISBN 0-13-141155-1。