tags:

views:

125

answers:

3

Using sockets in C, is it safe to do this in a function?

int ConnectTo(char *ip, int port){
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    inet_pton(AF_INET, ip, &addr.sin_addr.s_addr);
    addr.sin_port = htons(port);

    int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(connect(sock, (struct sockaddr *) &addr, sizeof(addr))
        return sock;
    else
        return -1;
}

More specifically, the prototype given in 'man connect' is

int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

Will I be punished somewhere down the line if the sockaddr structure is trashed later?

A: 

I've never had a problem doing it that way. The socket structure must hold the sockaddr data afterward.

wallyk
A: 

The reason the sockaddr is passed as a pointer is because it is a structure and they want to avoid copying it unnecessarily, which is would what would happen if it was passed as a value. A pointer is typically as big as a single memory word - 32 or 64 bits in most cases. A sockaddr struct is quite big, on my platform its at least 18 bytes.

Logically it would be quite hard for another function down the line to access that pointer, The only way that could ever happen was if the connect() function stored that pointer globally somewhere which is totally nuts and wouldn't make any sense and if there was ever a socket API that did that you should either kill yourself or the developer of that implementation.

rep_movsd
So, just to be completely clear, I should preserve the sockaddr structure because once this function is popped off the stack the structure's memory is fair game (and free it when I close the socket)? Seems completely logical to me, I was mostly curious as to whether or not sockets continues to use that structure long after connecting, which would lead to destruction if the memory is trashed.
Asuah
No, you need not preserve that...The connect() function is done with the sockaddr once it returns, as i said in my reply, no sane implementation of connect() would try to access that memory again....
rep_movsd
+1  A: 

What you're doing is completely safe - the socket takes a copy of anything that it needs from the sockaddr.

caf
Exactly what I was looking for, thanks!
Asuah