LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Kernel (https://www.linuxquestions.org/questions/linux-kernel-70/)
-   -   Typecast struct sockaddr in struct sockaddr_in (https://www.linuxquestions.org/questions/linux-kernel-70/typecast-struct-sockaddr-in-struct-sockaddr_in-704943/)

sudhansu 02-16-2009 12:16 AM

Typecast struct sockaddr in struct sockaddr_in
 
Hello Everybody,
I have a very interesting problem while making a simple client server program in c. i am wokring on linux kernel-2.6.23.1 . While creating a socket for my server program i want to bind it with a port. for which i used following code


struct sockaddr_in sad;
memset((char *)&sad,0,sizeof(sad)); /* clear sockaddr structure */
sad.sin_family = AF_INET; /* set family to Internet */
sad.sin_addr.s_addr = INADDR_ANY; /* set the local IP address */
sad.sin_port = htons((u_short)port);/* set the port number */

if (bind(welcomeSocket, (struct sockaddr *)&sad, sizeof(sad)) < 0)
{
fprintf(stderr,"bind failed\n");
return 1;
}

Now in this bind call sad is converted in struct sockaddr *. Now after this code what i want to do for some experiment

struct sockaddr *a;
struct sockaddr_in *b;
a=(struct sockaddr *)&sad;
b=(struct sockaddr_in *)a;

now i want to extract all the members of structure b .. but i am getting incompatible reference pointer error. I just want to typecats a struct sockaddr into sockaddr_in and extract all of its data members. Please help me.

Thank you in advance...

stevexyz 02-17-2009 10:33 AM

You could extract them like this:

((struct sockaddr_in *)&sad)->sin_family
((struct sockaddr_in *)&sad)->sin_port
((struct sockaddr_in *)&sad)->sin_addr

Cheers, Steve


All times are GMT -5. The time now is 02:02 PM.