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"); |
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. |
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().
|
Quote:
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"); |
This is what I do and it works.
Code:
struct sockaddr_in sin; |
All times are GMT -5. The time now is 05:21 PM. |