Address Stucture for recvfrom vs. sendto

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kardon33
    New Member
    • May 2007
    • 158

    #1

    Address Stucture for recvfrom vs. sendto

    Is there a difference between the way the function recvfrom and sendto use the address structure.

    When i use sento it works fine, but when I try and use recvfrom with the same variables it errors out with (bad address).

    Or is there a better way to receive packets from a socket that i just sent to.

    Theres some of my source code.
    Code:
        struct sockaddr_in a;
      	a.sin_family = AF_INET;
      	a.sin_addr.s_addr = htonl(INADDR_ANY);
      	a.sin_port = htons(DefaultPort);
      	int sock;
      	sock = socket(AF_INET, SOCK_DGRAM, 0);  
      	
      	int fBroadcast = 1;
      	int err = setsockopt(sock, SOL_SOCKET, SO_BROADCAST, "C", 5);
      	if (err == -1) { perror("setsockopt"); 	exit(1); }		
      
      	//Binding the address to the socket
      	err = bind(sock, (struct sockaddr *)&a, sizeof(a));
      	if (err == -1) { perror("bind"); exit(1); }	
      
      
      	//Putting the ip address in the socket output address structure
      	a.sin_addr.s_addr = inet_addr(ip);
      
    
      	//Sending the information to the specified port
      	if (sendto(sock, packet, len, 0,	(struct sockaddr *)&a, sizeof(a)) == -1)
      	{ perror("sendto"); exit(1);  }
      	
      	int rcv;
      	char buf[300];
      	
       	// Recieve
      	rcv = recvfrom(sock, buf, 208, MSG_WAITALL, (struct sockaddr *)&a , sizeof(a));
        if(rcv == -1) { perror("recvfrom"); exit(1); }
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    The variable a is a struct sockaddr_in.

    You typecast the address of a to a struct sockaddr*.

    The only way this will work is if struct sockaddr_in and struct sockaddr have the same members and each member has the same size.

    Otherwise, you can't make a struct sockaddr out of a struct sockaddr_in just by typecasting an address.

    Comment

    • thespartan
      New Member
      • Apr 2010
      • 1

      #3
      Hi kardon33, did you find out the cause of the error. I also face same problem. The sendto with similar signature is able to send out packets, but recvfrom throws bad address, any one ideas?

      Comment

      Working...