0

I am trying to study and understand BSD socket programming using these simple example C++ code for TCP-IP server and client. I have read the standard APIs like socket(), bind(), listen(), accept() and read/recv() and even got code below to compile on g++/Linux.

What I want to do is see it working in real-life, I mean run the server code, and then connect to it using the client and send data from client-to-server and vice-a-versa and verify the data received. All this within two linux boxes(Ubuntu) in my same network segment. I have private IPv4 addresses given to those two Linux machines.

What should be the setup to achieve this and what code changes in the server and client code below, would be needed to achieve this over the network setup described above? I want to really see it working over network in real time?

Also any further pointers to code, blog articles to study hands-on socket programming/network programming would help.

//TCP SERVER
#include<sys/socket.h> 
#include<netinet/in.h> 
#include<stdio.h> 
#include<string.h>
#include<stdlib.h> 
#include <arpa/inet.h>
//#include <fcntl.h>
#include <unistd.h>

main()
{ 
    char buf[100]; 
    socklen_t len; 
    int k,sock_desc,temp_sock_desc; 
    struct sockaddr_in client,server; 
    memset(&client,0,sizeof(client)); 
    memset(&server,0,sizeof(server)); 
    sock_desc = socket(AF_INET,SOCK_STREAM,0); 
    server.sin_family = AF_INET; server.sin_addr.s_addr = inet_addr("127.0.0.1"); 
    server.sin_port = 7777; 
    k = bind(sock_desc,(struct sockaddr*)&server,sizeof(server)); 
    k = listen(sock_desc,20); len = sizeof(client);
    temp_sock_desc = accept(sock_desc,(struct sockaddr*)&client,&len); 
    while(1)
    {     
        k = recv(temp_sock_desc,buf,100,0);     
        if(strcmp(buf,"exit")==0)        
            break;     
        if(k>0)         
            printf("%s",buf); 
    } close(sock_desc); 
    close(temp_sock_desc); 
    return 0; 
}

//TCP CLIENT
#include<sys/socket.h> 
#include<netinet/in.h> 
#include<stdio.h> 
#include<string.h> 
#include<stdlib.h>
#include <arpa/inet.h>
//#include <fcntl.h>
#include <unistd.h>

main()
{ 
    char buf[100]; 
    struct sockaddr_in client; 
    int sock_desc,k; 
    sock_desc = socket(AF_INET,SOCK_STREAM,0);
    memset(&client,0,sizeof(client)); 
    client.sin_family = AF_INET; 
    client.sin_addr.s_addr = inet_addr("127.0.0.1"); 
    client.sin_port = 7777; 
    k = connect(sock_desc,(struct sockaddr*)&client,sizeof(client)); 
    while(1)
    {     
        gets(buf);     
        k = send(sock_desc,buf,100,0);     
        if(strcmp(buf,"exit")==0)         
            break; 
    } 
    close(sock_desc); 
    return 0; 
}
3
  • So what did you try, and what happened? Commented Feb 8, 2012 at 17:45
  • Is this the simplest example you could find? Commented Feb 8, 2012 at 17:45
  • @Useless I executed the server code as a executable on a Linux terminal. On another terminal on same box, i executed the client code. Typed something on the client executable terminal window. Nothing received on server.Thats what i want to understand how is this flow of data going to happen in thse socket code examples. Commented Feb 8, 2012 at 17:48

4 Answers 4

5

Add some error handling to your code, that will likely reveil something, eg:

Server:

#include <sys/socket.h>  
#include <netinet/in.h>  
#include <stdio.h>  
#include <string.h> 
#include <stdlib.h>  
#include <arpa/inet.h> 
//#include <fcntl.h> 
#include <unistd.h> 

main() 
{  
    int sock_desc = socket(AF_INET, SOCK_STREAM, 0);
    if (sock_desc == -1)
    {
        printf("cannot create socket!\n");
        return 0;
    }

    struct sockaddr_in server;  
    memset(&server, 0, sizeof(server));  
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;  
    server.sin_port = htons(7777);  
    if (bind(sock_desc, (struct sockaddr*)&server, sizeof(server)) != 0)
    {
        printf("cannot bind socket!\n");
        close(sock_desc);  
        return 0;
    }

    if (listen(sock_desc, 20) != 0)
    {
        printf("cannot listen on socket!\n");
        close(sock_desc);  
        return 0;
    }

    struct sockaddr_in client;  
    memset(&client, 0, sizeof(client));  
    socklen_t len = sizeof(client); 
    int temp_sock_desc = accept(sock_desc, (struct sockaddr*)&client, &len);  
    if (temp_sock_desc == -1)
    {
        printf("cannot accept client!\n");
        close(sock_desc);  
        return 0;
    }

    char buf[100];  
    int k;  

    while(1) 
    {      
        k = recv(temp_sock_desc, buf, 100, 0);      
        if (recv == -1)
        {
            printf("\ncannot read from client!\n");
            break;
        }

        if (recv == 0)
        {
            printf("\nclient disconnected.\n");
            break;
        }

        if (k > 0)          
            printf("%*.*s", k, k, buf);  

        if (strcmp(buf, "exit") == 0)         
            break;      
    }

    close(temp_sock_desc);  
    close(sock_desc);  

    printf("server disconnected\n");
    return 0;  
} 

Client:

#include <sys/socket.h>  
#include <netinet/in.h>  
#include <stdio.h>  
#include <string.h>  
#include <stdlib.h> 
#include <arpa/inet.h> 
//#include <fcntl.h> 
#include <unistd.h> 

main() 
{  
    int sock_desc = socket(AF_INET, SOCK_STREAM, 0); 
    if (sock_desc == -1)
    {
        printf("cannot create socket!\n");
        return 0;
    }

    struct sockaddr_in client;  
    memset(&client, 0, sizeof(client));  
    client.sin_family = AF_INET;  
    client.sin_addr.s_addr = inet_addr("127.0.0.1");  
    client.sin_port = htons(7777);  

    if (connect(sock_desc, (struct sockaddr*)&client, sizeof(client)) != 0)
    {
        printf("cannot connect to server!\n");
        close(sock_desc);
    }

    char buf[100];
    char c = '\n';
    char *p_buf;
    int k, len;  

    while(1) 
    {      
        gets(buf);

        len = strlen(buf);
        p_buf = buf;

        while (len > 0)
        {
            k = send(sock_desc, p_buf, len, 0);      
            if (k == -1)
            {
                printf("cannot write to server!\n");
                break;
            }

            p_buf += k;
            len -= k;
        }

        k = send(sock_desc, &c, 1, 0);      
        if (k == -1)
        {
            printf("cannot write to server!\n");
            break;
        }

        if (strcmp(buf, "exit") == 0)          
            break;  
    }  

    close(sock_desc);  
    printf("client disconnected\n");

    return 0;  
} 
Sign up to request clarification or add additional context in comments.

2 Comments

When the return from send() or recv() is -1 you should always check to see if errno is set to EINTR, and repeat the same call if so. Otherwise you can have unexplained failures due to interruptions.
nice sample code! thanks Remy! I can learn a lot from your coding style
2

On the server side you will need to change the address 127.0.0.1 to 0.0.0.0 to enable connections from anywhere. You can also use telnet instead of your client code and therefore check that the server is working as expected. Also investigate if you have the snoop command on your variety of Linux.

On the client side you need to use the IP address of the server machine

1 Comment

Tried below changes but could not see any connection being made/data trasnfer 1] Changed server code socket ip address to 0.0.0.0 . Build. Execute. Then from another terminal tried to ssh(telnet is blocked on the Linux PC) . What exactly you meant when u said use telnet. 2] Also changed client code socket address to the actual private ip address on which executed the server code. same behaviour no transfer or connection happening that i could see. Have i misunderstood something ? Could the port number used in this examples be problems?
2

You need to make the following changes.

Port number - use htons i.e.

server - server.sin_port = htons(7777); client - client.sin_port = htons(7777);

Server - get it to accept from any address - i.e. server.sin_addr.s_addr = INADDR_ANY;

Hope that helps somewhat

Comments

0

it should be like this.

if (connect(sock_desc, (struct sockaddr*)&client, sizeof(client)) != 0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.