Socket Programming in C

20 Dec 2014

This program let you know your external ip address. This program extract the response of www.curlmyip.com. It will print the entire response of the server (which includes the header).

Linux Code

#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<errno.h>
#include<netinet/in.h>
#include<netdb.h>
#include<arpa/inet.h> //for inet_ntoa

char msg[500]="GET / HTTP/1.0\nHost: www.curlmyip.com\n\n";
char response[10000];

int main()
{
        int socketi;

        struct sockaddr_in server;
        struct hostent *he;

        he=gethostbyname("www.curlmyip.com");

        server.sin_port=htons(80);

        server.sin_addr.s_addr=inet_addr(inet_ntoa(*((struct in_addr *)he->h_addr)));//inet_addr("184.106.112.172");
        server.sin_family=AF_INET;

        socketi=socket(AF_INET,SOCK_STREAM,0);

        if((connect(socketi,(struct sockaddr*)&server,sizeof(server))<0)){
                printf("\nCannot connect to server.");
                return -1;
        }
        int size=0;
        memset(response,0,sizeof(response));
        send(socketi,msg,sizeof(msg),0);
        int size_response=sizeof(response);
        while((size=recv(socketi,response+size,size_response,0))>0){
                //response[size]=0;
                size_response-=size;
        }
        printf("\n%s",response);
        close(socketi);

}

Windows code

#include <stdio.h>
#include <conio.h>
#include <winsock2.h>

#pragma comment (lib, "ws2_32.lib")


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

	WSADATA wsa;
	SOCKET socketi;
	char msg[1000]="GET / HTTP/1.0\nHost:www.curlmyip.com\n\n";
	char response[1000];
	int len=sizeof(response);
	int size=0;
	struct sockaddr_in server;


	if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
	{
		printf("Failed. Error Code : %d",WSAGetLastError());
		return -1;
	}

	if((socketi=socket(AF_INET,SOCK_STREAM,0))==INVALID_SOCKET){
		printf("Error creating Socket");
		return -1;
	}

	server.sin_family=AF_INET;
	server.sin_port=htons(80);
	server.sin_addr.s_addr=inet_addr("184.106.112.172");

	if(connect(socketi,(struct sockaddr *)&server,sizeof(server))<0){
		printf("\nConnect error");
		return  -1;
	}
	memset(response,0,sizeof(response));
	send(socketi,msg,sizeof(msg),0);
	while((size=recv(socketi,response+size,len,0))>0)
	{
	}
	
	printf("\n%s",response);

}