Chat/Messenger program using c

20 Dec 2014

Messages send through server program will be displayed in the client side. Port used is 10000. You can change the ip address of server in the client side program. Will update the program to include more features. The program is intended to use in Linux platform. (Compiler used is gcc).

Server

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

#define PORT 10000

int main(int arg,char *argc[])
{
        int socketn,acceptn;
        char msg[256]="Hello";

        struct sockaddr_in server;

        printf("Enter Message\n============\n");

        socketn=socket(AF_INET,SOCK_STREAM,0);

        server.sin_port=htons(PORT);
        server.sin_family=AF_INET;                      //Internet not local
        server.sin_addr.s_addr=htonl(INADDR_ANY); //Connect to any address

        if(bind(socketn,(struct sockaddr*)&server,sizeof(server))<0){
                printf("Failed to bind");
                exit -1;
        }
        if(listen(socketn,5)==-1){
                printf("Failed to listen");
                exit -1;
        }


        while(1)
        {
                printf(":>");
                scanf("%s",msg);
                acceptn=accept(socketn,(struct sockaddr*)NULL,NULL);
                write(acceptn,msg,sizeof(msg));
                close(acceptn);
                sleep(1);
        }
}

Client

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

#define PORT 10000

struct sockaddr_in client;
char msg[256];
struct sockaddr_in client;
int socketn,n;

void receive();

int main()
{
        client.sin_family=AF_INET;
        client.sin_port=htons(PORT);
        client.sin_addr.s_addr=inet_addr("127.0.0.1");

        while(1)
        {
                receive();
                sleep(1);
        }
}

void receive()
{
        if((socketn=socket(AF_INET,SOCK_STREAM,0))<0){
                printf("Cannot create socket.");
                exit -1;
        }

        bind(socketn,(struct sockaddr*)&client,sizeof(client));

        if((connect(socketn,(struct sockaddr*)&client,sizeof(client)))<0){
                printf("Cannot create connection");
                exit -1;
        }

        read(socketn,msg,sizeof(msg));
        printf(":>%s\n",msg);
        sleep(1);

}