Can any one tell me how to set the Source port address in the UDP socket ?. My client application needs to send the Packets from the 57002 port to the server port 58007 .
Source port – The port of the device sending the data. This field can be set to zero if the destination computer doesn't need to reply to the sender. Destination port – The port of the device receiving the data. UDP port numbers can be between 0 and 65,535.
The steps of establishing a UDP socket communication on the server side are as follows: Create a socket with the socket() function; Bind the socket to an address using the bind() function; Send and receive data by means of recvfrom() and sendto().
The CONNECT command enables an application to associate a socket with the socket name of a peer. The socket then is considered to be a connected UDP socket. You can call the CONNECT command multiple times with different peer names to change the socket association.
#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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With