views:

504

answers:

3

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

Basically I'm just listening 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 set up and bound to a port of choice and awaits 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 the "Hello!" string right back to the sender.

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

But... what the ** does it mean? What file? What is too long?

Is it that I can't reuse the socket to send data back, or have I just made another newb mistake?

Best regards,

+9  A: 

You should not be passing the address of the socket structure length to sendto() - it requires the actual length (i.e., "addr_len", not "&addr_len").

The reason you pass the address of the length to recvfrom() is that it is changed by that function if the real address happens to be 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) {
paxdiablo
+1  A: 

Erm, at a minimum the '&addr_len' you passed in sendto probably should have not been passed by address: ie: should have just been addr_len.

Joe
A: 

Great, that was it. Thanks!

I think I'd do better noting what error codes actually means. :)

rhardih
You should put these kind of posts in the comment section :)
Daniel
And don't forget to mark an answer as accepted. Welcome to SO!
Daniel
Noted, thx :) (fill)
rhardih