0

I just started to learn socket programming and found this unusual argument in the connect() function.

(struct sockaddr *)&server 

snippet of socket() function:

if (connect(s , (struct sockaddr *)&server , sizeof(server)) < 0)
{
    puts("connect error");
    return 1;
}
user207421
  • 305,947
  • 44
  • 307
  • 483
Kishor
  • 450
  • 8
  • 11
  • possible duplicate of [Why do we cast sockaddr\_in to sockaddr when calling bind()?](http://stackoverflow.com/questions/21099041/why-do-we-cast-sockaddr-in-to-sockaddr-when-calling-bind) – edmz Mar 31 '15 at 18:37
  • Why did you mention `socket()` three times when your question is about `connect()`? – user207421 Mar 31 '15 at 19:18
  • What is your question? – Julian Mar 31 '15 at 19:22

3 Answers3

2

If you are confused by why a pointer to server, which I assume is of type sockaddr_in is not passed to the function and instead it is cast to a pointer to struct sockaddr, then here is your answer:

The struct sockaddr_in is just a wrapper structure for struct sockaddr:

struct sockaddr {
    unsigned short sa_family;
    char           sa_data[14];
};

The port number and the ip address are held together here. They are held together in sa_data[14]- the first 2 bytes holding the port number, and the next 4 bytes holding the ip address. The remaining 8 bytes are unused. These are the 8 bytes you clear to zeroes via sin_zero[8] when you use sockaddr_in.

Functions like connect() does not know of any type struct sockaddr_in, they only know of struct sockaddr.

Arjun Sreedharan
  • 11,003
  • 2
  • 26
  • 34
1

The server is the protocol address of the host you're connecting to. If it's IPv4 socket, you should be using struct sockaddr_in* cast into struct sockaddr*, if it's IPv6 socket, you should be using struct sockaddr_in6* cast into struct sockaddr*.

juhist
  • 4,210
  • 16
  • 33
  • no I am just confused with the syntax and casting and such... please help me with that... – Kishor Mar 31 '15 at 17:38
  • Well, it expects you to give a pointer, hence `&server` and not `server`. And because it's used for all protocols that have different `sockaddr_foo` structures you cast it into `struct sockaddr*`, a common struct for all protocols. Hence `(struct sockaddr*)&server`. – juhist Mar 31 '15 at 17:44
  • Maybe this helps: http://stackoverflow.com/questions/21099041/why-do-we-cast-sockaddr-in-to-sockaddr-when-calling-bind – cadaniluk Mar 31 '15 at 17:46
1

The sockaddr structure is used to store an Internet Protocol (IP) address for a machine participating in a Windows Sockets communication. the connect() function is used at the client side to connect with the server. So the second argument is basically filled with the server IP and port information, so that client can connect with the server identified by IP and Port

Yasir Majeed
  • 739
  • 3
  • 12