Socket Programming in C

Ok, so I'm trying to get UDP code to work, and I'm barely green when it comes to network programming using C. I use the sample file from here

Basically, I just listen for incoming UDP packets on a given port, and then I want to send some data back the same way. Below is the relevant part.

At this point, the socket is configured and bound to the select port and is waiting for incoming packets:

printf("GSProxy: waiting to recvfrom...\n"); addr_len = (socklen_t) sizeof their_addr; if ((numbytes = recvfrom(sockfd, buf, MAXBUFLEN-1 , 0, (struct sockaddr *)&their_addr, &addr_len)) == -1) { // argument 6 gives a warning but is correct int perror("recvfrom"); exit(1); } printf("GSProxy: got packet from %s\n", inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s)); printf("GSProxy: packet is %d bytes long\n", numbytes); buf[numbytes] = '\0'; printf("GSProxy: packet contains \"%s\"\n", buf); char retmsg[] = "Hello!"; if ((numbytes = sendto(sockfd, retmsg, 7, 0, (struct sockaddr *) &their_addr, &addr_len)) == -1) { perror("GSPProxy: sendto"); exit(1); } printf("GSProxy: Sent %i bytes.\n", numbytes); 

I just want to send "Hello!". string back to the sender.

This does not work with the error " GSPProxy: sendto: File name too long ". Which is the error code [ENAMETOOLONG], as far as I can tell.

But what does this mean **? Which file? What is too long?

Is it that I cannot reuse the socket to send data, or have I just made another newb error?

Yours faithfully,

+4
source share
2 answers

You should not pass the address of the socket structure length to sendto() - this requires the actual length (ie "addr_len" , not "&addr_len" ).

The reason you pass in an address of length recvfrom() is because it is changed by this function if the real address becomes shorter.

In other words, replace:

 if ((numbytes = sendto (sockfd, retmsg, 7, 0, (struct sockaddr *) &their_addr, &addr_len)) == -1) { 

with:

 if ((numbytes = sendto (sockfd, retmsg, 7, 0, (struct sockaddr *) &their_addr, addr_len)) == -1) { 
+14
source

The Erm, at a minimum, '& addr_len', which you passed to sendto, should probably not have been passed to: ie: there should have been only addr_len.

+1
source

All Articles