Thread: getsockname() bad address error

  1. #1
    Registered User
    Join Date
    Apr 2004
    Posts
    2

    getsockname() bad address error

    I'm trying to retrieve the random port number the kernel assigned to my socket. Unfortunately getsockname() keeps throwing a bad address error and I have no idea why.... Hopefully someone can provide some assistance.

    Below is the code segment:
    Code:
        struct sockaddr_in target, me;
        int rc, sd;
    
        /* set target struct info*/
        target.sin_family = target_address->h_addrtype;
        memcpy((char *) &target.sin_addr.s_addr, 
                target_address->h_addr_list[0], target_address->h_length);
        target.sin_port = target_port;
    
        /* create socket */
        if ((sd = socket(AF_INET, SOCK_DGRAM, 0)) == -1){
            perror("socket");
    	exit(1);
        }
    
        /* bind socket to random port */
        me.sin_family = AF_INET;
        me.sin_addr.s_addr = INADDR_ANY;
        me.sin_port = 0;
        if ((bind(sd, (struct sockaddr *) &me, sizeof(me))) == -1){
            perror("bind");
            exit(1);
        }
    
        /* connect UDP socket */
        if ((rc = connect(sd, (struct sockaddr *) &target, sizeof(target)))){
            perror("connect");
            exit(1);
        }
    
        /* get random port */
        if (getsockname(sd, (struct sockaddr *) &me, (int *)sizeof(me)) == -1){
            perror("getsockname");
    	//exit(1);
        }
        printf("Listening on port %d\n", me.sin_port);

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > (int *)sizeof(me)
    This should be a pointer to a variable (of whatever type) containing the value sizeof(me)

    socklen_t foo = sizeof(me);
    getsockname(sd, (struct sockaddr *) &me, &foo )
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Apr 2004
    Posts
    2
    Ah! much thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how do you resolve this error?
    By -EquinoX- in forum C Programming
    Replies: 32
    Last Post: 11-05-2008, 04:35 PM
  2. Avoiding Global variables
    By csonx_p in forum Windows Programming
    Replies: 32
    Last Post: 05-19-2008, 12:17 AM
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  4. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM
  5. pointer to array of objects of struct
    By undisputed007 in forum C++ Programming
    Replies: 12
    Last Post: 03-02-2004, 04:49 AM