# socket programming



## bkouhi (May 31, 2013)

Hi.

Here is my code:


```
int
main(int argc, char *argv[])
{

        int sockfd;

        unsigned short port = 1234;

        char *address = "127.0.0.1";
        char message[BUFSIZ];

        struct sockaddr_in connection;

        if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
        {
                printf("socket error\n");
                exit(EXIT_FAILURE);
        }

        connection.sin_addr.s_addr = inet_addr(address);
        connection.sin_port = htons(port);
        connection.sin_family = AF_INET;
        memset( &(connection.sin_zero), '\0', 8 );

        if( (connect(sockfd, (struct sockaddr*)&connection, sizeof(struct sockaddr))) == -1);
        {
                printf("connect error\n");
                exit(EXIT_FAILURE);
        }

        for(;;)
        {
                scanf("%s", &message);
                send(sockfd, message, sizeof(message), 0);
        }

        close(sockfd);

        return 0;
}
```

In one terminal:
`nc -k -l 127.0.0.1 1234`

And in another one:

```
[CMD]./a.out[/CMD]
connect error
```

What's wrong with this code?


----------



## Anonymous (May 31, 2013)

bkouhi said:
			
		

> ```
> int main(int argc, char *argv[])
> {
> int sockfd;
> ...



The errors are marked  with red color:

 Replace sockaddr with sockaddr_in
 Remove the semicolon at the end of the if() statement
 Remove the address operator & in the scanf() statement
 Replace sizeof() with strlen()
Best regards

Rolf


----------



## nslay (May 31, 2013)

You might also find getaddrinfo(3) a better and more convenient way to set these structures up. For as general and powerful as sockets are, the whole type punning is just an awful mess ...


```
const char *address = "127.0.0.1";
const char *port = "1234";
struct addrinfo hints, *res = NULL;
int e;

memset(&hints, 0, sizeof(hints));

hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_NUMERICHOST; /* Just leave this as 0 if you want it to work in the general case of either an address or hostname */

e = getaddrinfo(address, port, &hints, &res);

if (e != 0) {
  fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(e));
  return -1;
}

if (connect(sockfd, res->ai_addr, res->ai_addrlen) == -1) {
  perror("connect");
  freeaddrinfo(res);
  return -1;
}

freeaddrinfo(res);

/* ... */
```

Hope this helps...


----------

