News for hackers. Stuff that matters.
Re:Socket programming – well commented examples by greenyoda on Saturday February 21, 2015 @09:15PM (#9087893)
I don't understand how this code in client.c works:

    char filler[16] = {0};
    ...
    filler[0] = (unsigned short)AF_INET;
    filler[2] = (unsigned short)htons(port);
    filler[4] = (unsigned long)htonl(INADDR_ANY);
In C, sizeof(char) is one byte. Since htons() returns a short (the port number in network order), wouldn't you get an overflow and lose data when you assign it to filler[2]?

(And similarly for filler[4].)

Re:Socket programming – well commented examples by rainbowgarden on Sunday February 22, 2015 @06:44AM (#9089074)
It will overflow to filler[3]. ie the 4th byte. see the struct sockaddr:

	 * first 2 bytes: Address Family,

	 * next 2 bytes: port,

	 * next 2 bytes: ipaddr,

	 * next 8 bytes: zeroes.
so filler[2] and filler[3] will form a short which will contain the port number.
Re:Socket programming – well commented examples by greenyoda on Sunday February 22, 2015 @01:07PM (#9090247)
"It will overflow to filler[3]"

Not with any correct C compiler, it wont. Here's a simple test program I ran on Linux:

    #include <stdio.h>

    int main()
    {
      char filler[16] = {0};
      int i;
      unsigned short s1 = 0xFFFF;
      unsigned long  l1 = 0xFFFFFFFF;

      filler[0] = (unsigned short)s1;
      filler[2] = (unsigned short)s1;
      filler[4] = (unsigned long)l1;

      for (i = 0; i < 8; i++)
        printf("filler[%d] = %d\n", i, filler[i]);
    }
And when you run it, all the elements of filler that haven't been explicitly assigned to are still 0, even though the unsigned shorts and longs that were assigned to them have '1' in all their bits:

    $ gcc filler.c
    $ ./a.out
    filler[0] = -1
    filler[1] = 0
    filler[2] = -1
    filler[3] = 0
    filler[4] = -1
    filler[5] = 0
    filler[6] = 0
    filler[7] = 0
Since htons() swaps the bytes in its result, you should just be able to assign the value it returns directly:

    struct sockaddr_in serv_addr;
    ...
    serv_addr.sin_port = htons(port);
(See, for example: https://en.wikibooks.org/wiki/C_Programming/Networking_in_UN...)