LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to specify source port when sending UDP packet (https://www.linuxquestions.org/questions/programming-9/how-to-specify-source-port-when-sending-udp-packet-484816/)

socialjazz 09-18-2006 09:52 PM

How to specify source port when sending UDP packet
 
I want to send UDP packet from a specify source port
how do i do that? When i try to send a UDP packet, the system will ususally find a source port for me.

my present code is:


struct sockaddr_in si_other;
int s, i, slen=sizeof(si_other);
char buf[BUFLEN] = {0xa,0xd};

if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
printf("socket() failed\n");

memset((char *) &si_other, sizeof(si_other), 0);
si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);
if (inet_aton(SRV_IP, &si_other.sin_addr)==0) {
printf("inet_aton() failed\n");
}

if (sendto(s, buf, BUFLEN, 0, &si_other, slen)==-1)
printf("sendto() failed\n");

Wim Sturkenboom 09-18-2006 10:58 PM

How do you mean, usually find a source port

http://www.cs.utah.edu/~swalton/list...kets/programs/ The coonection-less sender and connectionless-receiver in chapter 4 give examples of UDP programming.

randyding 09-18-2006 11:43 PM

Its done with bind(), it takes a struct sockaddr * where you can set the local interface address (if there is more than 1) and local port number. Binding is normally done immediately after calling socket().

socialjazz 09-19-2006 01:56 AM

Quote:

Originally Posted by randyding
Its done with bind(), it takes a struct sockaddr * where you can set the local interface address (if there is more than 1) and local port number. Binding is normally done immediately after calling socket().

Thanks for replying.
What should is use for the sin_addr.s_addr address?
my code does not allow me to send packet thru udp anymore if i add the following:

memset((char *) &si_me, sizeof(si_me), 0);
si_me.sin_family = AF_INET;
si_me.sin_port = htons(PORT);

si_me.sin_addr.s_addr = htonl(INADDR_ANY);

if (bind(s, &si_me, sizeof(si_me))==-1)
printf("bind() failed\n");

randyding 09-19-2006 08:15 PM

This is what I do and it works.
Code:

struct sockaddr_in sin;

if (-1==(sock=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP))) return 0;
memset(&sin,0,sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_port=htons(fromport);
sin.sin_addr.s_addr=INADDR_ANY;
if (-1==bind(sock,(struct sockaddr *)&sin,sizeof(struct sockaddr_in))) return 0;

Edit: I just noticed your memset() arguments are ordered wrong.


All times are GMT -5. The time now is 05:21 PM.