[RESOLVED] Socket Programming Client/Server Over the Internet Question
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7

Thread: [RESOLVED] Socket Programming Client/Server Over the Internet Question

  1. #1
    Join Date
    Apr 2009
    Posts
    2

    [RESOLVED] Socket Programming Client/Server Over the Internet Question

    Hello everyone,
    I am trying to make a Client/Server Socket Program that can connect between two computers over the Internet. What the program does is just send messages back and forth, like a very basic IM. I have been successful so far in connecting two computers within the same network (like at my school) but unsuccessful at connect my laptop to my computer back at my house. I have looked on the Internet for answers and my professor talked about using a DNS resolver but I am still a bit confused on what I need to do in order to get the client and server programs to connect to each other. I've read that the gethostbyname() function is supposed to have something to do with the DNS resolver but I'm still a bit confused as to if I am using it correctly. There are two executables server.exe and client.exe. Both server.c and client.c use another c file called talk.c. This is where the send() and recv() functions are to send and receive data. Here is the code:

    Server.c:
    Code:
    #include	<winsock2.h>
    #include	<stdio.h>
    #include	<string.h>
    
    #define HOSTNAMELEN     128
    #define BUFLEN  80
    
    
    
    int main(int argc, char *argv[]) {
    	void runTalk(SOCKET);
    
    	char serverHostName[HOSTNAMELEN];
    	int on = 1;
    	int port;
    	int clientLen;
    	int newSkt, skt;
    	int length;
    	SOCKADDR_IN client;			// Client's IP address
    	SOCKADDR_IN listener;		// Server's listener address
    	struct hostent  *host;		// Server's host information
    
    //WSAStartup parameters
    	WORD wVersionRequested; 
    	WSADATA wsaData; 
    
    
    	wVersionRequested = MAKEWORD(2, 2);		// Version 2.0
    	if(WSAStartup(wVersionRequested, &wsaData) != 0) {
    		fprintf(stderr, "Process failed on WinSock startup\n");
    		ExitProcess(0);
    	};
    
    
    // Get the server host name and port number from the command line
    	switch(argc) {
    	case 1:
    		if(gethostname(serverHostName, HOSTNAMELEN) != 0) {
    			fprintf(stderr, "Unable to get local host name\n");
    			fprintf(stderr, "Error number: &#37;d\n", WSAGetLastError());
    			ExitProcess(1);
     		}
    		break;
    	case 2:
    		strcpy(serverHostName, argv[1]);
    		break;
    	default:
    		fprintf(stderr, "Usage: client <port no.> [<server_host>]\n");
    		ExitProcess(0);
    	};
    	fprintf(stderr, "Server host: %s\n", serverHostName);
    	port = 0;	// Let bind choose the port number
    
    // Set up a socket for listening
    	skt = socket(AF_INET, SOCK_STREAM, 0);
    	host = gethostbyname(serverHostName);
    	ZeroMemory(&listener, sizeof(SOCKADDR_IN));
    	listener.sin_family = AF_INET;
    	listener.sin_port = htons((u_short) port);
    	CopyMemory(&listener.sin_addr, host->h_addr_list[0], host->h_length);
    	fprintf(stderr, "IP Address: %s\n", inet_ntoa(listener.sin_addr));
    
    // Advertise listener's name
    	if(bind(skt, (const struct sockaddr FAR *) &listener, sizeof(listener))) {
    		fprintf(stderr, "Bind error #%d\n", WSAGetLastError());
    		ExitProcess(1);
    	}
    // Report the port number to the user
    	length = sizeof(listener);
    	getsockname(skt, (struct sockaddr FAR *) &listener, &length);
    	fprintf(stderr, "Server port number: %d\n", ntohs(listener.sin_port)); 
    
    // Now begin waiting for a request
    	listen(skt, SOMAXCONN);
    	fprintf(stderr, "Listening ... ");
    
    // Wait for client requests
    	clientLen = sizeof(SOCKADDR_IN);
    	newSkt = accept(skt, (SOCKADDR *) &client, &clientLen);
    	fprintf(stderr, "accepted connection request \n");
    	closesocket(skt);			// Get rid of listener socket
    	runTalk(newSkt);
    
    // Clean up and quit
    	closesocket(newSkt);
    	WSACleanup();
    	return 0;
    }
    Client.c:
    Code:
    #include	<winsock2.h>
    #include	<stdio.h>
    #include	<string.h>
    
    #define	HOSTNAMELEN	128
    
    int main (int argc, char *argv[]) {
    	void runTalk(SOCKET);
    
    	int on = 1;
    	int port;       /* Internet port number */
    	char serverHostName[HOSTNAMELEN];
    	SOCKET skt;
    	LPHOSTENT  host;
    	SOCKADDR_IN listener;
    
    //WSAStartup parameters
    	WORD wVersionRequested; 
    	WSADATA wsaData; 
    
    
    // Must start the package before calling any WSA function
    	wVersionRequested = MAKEWORD(2, 2);		// Version 2.0
    	if(WSAStartup(wVersionRequested, &wsaData) != 0) {
    		fprintf(stderr, "Process failed on WinSock startup\n");
    		ExitProcess(0);
    	};
    
    // Get server name and port number
    	switch(argc) {
    	case 2:
    		if(gethostname(serverHostName, HOSTNAMELEN) != 0) {
    			fprintf(stderr, "Unable to get local host name\n");
    			fprintf(stderr, "Error number: %d\n", WSAGetLastError());
    			ExitProcess(1);
     		}
    		break;
    	case 3:
    		strcpy(serverHostName, argv[2]);
    		break;
    	default:
    		fprintf(stderr, "Usage: client <port no.> [<server_host>]\n");
    		fprintf(stderr, "(Must start Server first to get port no.)\n");
    		ExitProcess(0);
    	};
    	fprintf(stderr, "Server host: %s\n", serverHostName);
    	port = atoi(argv[1]);
    	fprintf(stderr, "Server port number: %d\n", port);
    
    // Set up a socket to talk to the server
    	skt = socket(AF_INET, SOCK_STREAM, 0);
    	host = gethostbyname(serverHostName);
    	ZeroMemory(&listener, sizeof(SOCKADDR_IN));
    	listener.sin_family = AF_INET;
    	listener.sin_port = htons((u_short) port);
    	CopyMemory(&listener.sin_addr, host->h_addr_list[0], host->h_length);
    
    	fprintf(stderr, "Making connection request ... ");
    	if	(connect(
    				skt,
    				(const struct sockaddr FAR *) &listener,
    				sizeof(SOCKADDR_IN))
    		!= 0
    		) {
    			fprintf(stderr, "Connect error #%d\n", WSAGetLastError());
    			ExitProcess(1);
    	};
    	fprintf(stderr, "connected\n");
    
    
    /* Run the local end of the talk session */
    	runTalk(skt);
    
    /* All done -- tear down the circuit */
    	closesocket(skt);
    
    	WSACleanup();
    	return 0;
    }
    Talk.c:
    Code:
    #include	<winsock2.h>
    #include	<winbase.h>
    #include	<conio.h>
    #include	<stdio.h>
    #include	<io.h>
    
    #define BUFLEN  80
    #define STDIN   0
    
    int errno;      // For nonblocking read flag
    
    
    void runTalk(SOCKET skt) {
    	int len;
    	int on = 1;
    	char buffer[BUFLEN];
    	int flags = 0;			// Used with recv
    	int numberRead;
    
    // Make socket nonblocking
    	ioctlsocket(skt, FIONBIO, &on);
    
    	printf(">");
    	fflush(stdout);
    	while (TRUE) {
    	// Poll the skt
    		if ((len = recv(skt, buffer, BUFLEN, flags)) > 0) {
    		// Incoming info from the remote process, write stdout
    			buffer[len] = '\0';
    			printf(buffer);
    			Sleep(100);
    			printf(">");
    			fflush(stdout);
    		}
    
    	// Poll the console
    		if(_kbhit()) {
    				numberRead = _read(STDIN, buffer, BUFLEN);
    				send(skt, buffer, numberRead, errno);
    				Sleep(100);
    				printf(">");
    				fflush(stdout);
    		}
    	}
    }
    Please let me know what you think! Thanks!

    Oh and the server.exe can be clicked on to run, but the client must be ran through the command prompt. The client.exe requires two command line parameters, the first being the port that the server has chosen and the second being the IP Address... Hope to get this working soon!
    Attached Files Attached Files
    Last edited by zebdor44; April 18th, 2009 at 02:43 AM.

  2. #2
    Join Date
    Mar 2004
    Location
    Singapore
    Posts
    47

    Re: Socket Programming Client/Server Over the Internet Question

    Quote Originally Posted by zebdor44 View Post
    I have been successful so far in connecting two computers within the same network (like at my school) but unsuccessful at connect my laptop to my computer back at my house. I have looked on the Internet for answers and my professor talked about using a DNS resolver but I am still a bit confused on what I need to do in order to get the client and server programs to connect to each other.
    There are a couple of possible reason why you can't connect to your home computer:
    1. Is one of the PC behind firewall (I am not talking about windows firewall)? *Usually your school will have a firewall.
    2. If one of the PC is in school, how do you usually access the web, through a proxy server? If yes, then you have to consider this proxy server in your code implementation.
    3. Is your home laptop hidden behind a router? Ensure that the laptop is using a visible public IP.

    As long as you have the correct network configuration and each machine IP addresses, you should be able to connect them both.
    Xander Tan

  3. #3
    Join Date
    Apr 2009
    Posts
    2

    Re: Socket Programming Client/Server Over the Internet Question

    thanks for the tips! i got it to work. I used port forwarding on my home router and it worked

  4. #4
    Join Date
    Mar 2004
    Location
    Singapore
    Posts
    47

    Re: Socket Programming Client/Server Over the Internet Question

    Quote Originally Posted by zebdor44 View Post
    thanks for the tips! i got it to work. I used port forwarding on my home router and it worked
    Now go for the DNS resolver,you can register your dynamic dns at http://www.dyndns.com/.
    Xander Tan

  5. #5
    Join Date
    Apr 2009
    Posts
    1

    Re: [RESOLVED] Socket Programming Client/Server Over the Internet Question

    Hello zebdor44,

    I am curious sthng about your code. Do you execute client and server .c files on different projects on the same computer. Or do you put both client, server and task .c files in the same project.
    Because when I execute it on different project, first I execute server.c and then when I compile client.c, It says that I should start server first but I guess I ve already started server when I execute server.c because it prints out that it is listening.

    I ll appreciate it if you help me asap.

    Thanks

  6. #6
    Join Date
    Sep 2009
    Posts
    1

    Re: [RESOLVED] Socket Programming Client/Server Over the Internet Question

    hey,
    need help!!
    I have copied the server.exe to another pc..but i cant run the exe file to test my program on 2 diff computer....why??

  7. #7
    Join Date
    Mar 2010
    Posts
    2

    Smile Re: [RESOLVED] Socket Programming Client/Server Over the Internet Question

    hi Frd.,

    i need the code which u have modifed and which worked accross internet could u mail me the codings as it would be very helpful for me...
    nezammca @ gmail com

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center