Anders Henriksson wrote:
> I am trying to learn socket programing on linux. I think I am getting the hang
> of most things but there is one utterly disturbing detail, I can't figure out
> how to manipulate the sockaddr structure used in the connect library call
> among others.
>
> In most code I have looked at another structure is used (sockaddr_in) but I
> cant find the definition of this or the format of the sockaddr structure.
>
> What I really would like is to find the definition of sockaddr_in.
`struct sockaddr_in' is defined in netinet/in.h, and is basically:
struct sockaddr_in
{
unsigned short int sin_family; /* Address family */
unsigned short int sin_port; /* Port number */
struct in_addr sin_addr; /* Internet address */
unsigned char sin_zero[8]; /* Pad to 16 bytes */
};
A `struct sockaddr' is basically an abstract type, which doesn't
specify the format of the address:
struct sockaddr
{
unsigned short int sa_family; /* Address family */
char sa_data[14]; /* Address data */
};
To specify an address and port, fill in a `struct sockaddr_in', then
cast its address to a `struct sockaddr *', e.g.
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv)
{
struct sockaddr_in r_addr;
int s;
if (argc != 3)
{
fprintf(stderr, "Usage: %s <IP address> <port>\n", argv[0]);
return 1;
}
s = socket(PF_INET, SOCK_STREAM, IPPROTO_IP);
if (s < 0)
{
perror("socket");
return 1;
}
r_addr.sin_family = AF_INET;
r_addr.sin_port = htons(atoi(argv[2]));
r_addr.sin_addr.s_addr = inet_addr(argv[1]);
if (connect(s, (struct sockaddr *) &r_addr, sizeof(r_addr)) == -1)
{
perror("connect");
return 1;
}
/* at this point, `skt' is a socket which is connected to
the specified IP address and port */
return 0;
}
--
Glynn Clements <[EMAIL PROTECTED]>