Thread: socket programming cannot connect

  1. #1
    Registered User
    Join Date
    Oct 2013
    Posts
    15

    socket programming cannot connect

    Hi everyone, I am writing client C socket program in Linux and server C# socket
    program in window. I am also running these 2 programs in different PCs. When I
    run client program it shows that "Cannot connect".
    my client C program in
    Linux is
    Code:
    #include <sys/socket.h>  //for socket(), connect(), sendto() and recvform()
    #include <sys/types.h>
    #include <netinet/in.h>
    #include <netdb.h>
    #include <stdio.h>  // for printf() and fprintf()
    #include <string.h>  //for memset()
    #include <stdlib.h>   //for atoi() and exit()
    #include <unistd.h>  //for close()
    #include <errno.h>
    #include <arpa/inet.h>  //for sockaddr_in and inet_addr()
     
    
    #define SERVERPORT 1234	
    
    int main ( )                      
    {
    	int sockfd, n;
    	struct sockaddr_in serv_addr;
    	struct hostent *serverINFO;
    	
    	char buffer[256];
    	char hostname[1024];
    	//struct hostent* h;
    	gethostname(hostname, sizeof(hostname));
    	serverINFO = gethostbyname(hostname);
    	
    	if(serverINFO == NULL)
    	{
    		printf("Problem interpreting host\n");
    		return 1;  
    	}
    	sockfd = socket(AF_INET, SOCK_STREAM, 0);
    	
    	if (sockfd < 0)
    		{
    			printf("Cannot create socket\n");
    			return 1;
    		}
    	inet_pton(AF_INET, "192.168.0.1",&(serv_addr.sin_addr));
    	//serv_addr.sin_family = serverINFO ->h_addrtype;
    	//memcpy((char *) &serv_addr.sin_addr, serverINFO->h_addr_list[0], serverINFO->h_length);
    	//serv_addr.sinport = htons(SERVERPORT);
    	//bzero((char *) &serv_addr, sizeof(serv_addr));
    	//serv_addr.sin_family = AF_INET;
    	//memcpy(&serv_addr.sin_addr, server->h_addr, server->h_length);
    	//bcopy((char *)server->h_addr,(char *)&serv_addr.sin_addr.s_addr,server->h_length);
    	serv_addr.sin_port = htons (SERVERPORT);
    	
    	if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof (serv_addr)) < 0) 
    		{
    			printf("Cannot connect\n");
    			return 1;
    		}
    	else
    		printf("Connected\n");
    	/*printf("Please enter the message: ");
    	bzero(buffer, 256);
    	fgets(buffer,255,stdin);
    	n = write(sockfd, buffer, strlen(buffer));
    	
    	if (n < 0)
    		printf ("ERROR writing to socket");
    	bzero(buffer, 256);
    	n = read (sockfd, buffer, 255);
    	
    	if (n < 0)   
    		printf ("ERROR reading from socket");
    	printf("here we are %s\n", buffer);
    	close(sockfd);*/
    }
    my server C# program in window is

    Code:
    namespace server_window
    {
        public partial class Form1 : Form
        {
              static TcpListener tcpListener = new TcpListener(IPAddress.Parse("192.168.0.2"), 1234);
            TcpClient socketForClient;
           EndPoint ep;
           public Form1()
            {
                InitializeComponent();
                BW_Connection.RunWorkerAsync();
            }
          
            private void BW_Connection_DoWork(object sender, DoWorkEventArgs e)
            {
                tcpListener.Start();
                socketForClient = tcpListener.AcceptTcpClient();
                ep = socketForClient.Client.RemoteEndPoint;
                  this.Invoke(new MethodInvoker(delegate { TB_text.Text = "Client connected..."; }));
            }
               private void Form1_FormClosing(object sender, FormClosingEventArgs e)
            {
                socketForClient.Close();
                
            }
    
        }
    }
    If my program is wrong, pls kindly let me know. Coz I am a bit new to socket
    programming and Linux. Thanks a lot..

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    I do not understand - on server you are usign TcpListener and on client you create socket with type 0 which is IP and not TCP

    Have you tried to put into the 3rd parameter of the socket() call IPPROTO_TCP?
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    Are you sure the server is actually reachable on this port from your client? Usually you can use telnet to verify this, e.g.:

    telnet 192.168.0.2 1234

    1. Also notice your server is listening on port 1234 but nowhere in your client do you say which port you want
    2. Why do you comment out lots of lines in your code? If its not related to your question theres no reason to post it here

  4. #4
    Registered User
    Join Date
    Oct 2013
    Posts
    15
    Quote Originally Posted by c99tutorial View Post
    Are you sure the server is actually reachable on this port from your client? Usually you can use telnet to verify this, e.g.:

    telnet 192.168.0.2 1234

    1. Also notice your server is listening on port 1234 but nowhere in your client do you say which port you want
    2. Why do you comment out lots of lines in your code? If its not related to your question theres no reason to post it here

    I had used ping to each IP address. So there is connection between them. And I used
    Code:
    serv_addr.sin_port = htons(SERVERPORT);
    which is port no 1234.

    so sorry to delete unused code.

  5. #5
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    ping does not verify that a particular port is open. The question is whether you can in fact make a connection using port 1234 from your client to your server

  6. #6
    Registered User
    Join Date
    Oct 2013
    Posts
    15
    Quote Originally Posted by vart View Post
    I do not understand - on server you are usign TcpListener and on client you create socket with type 0 which is IP and not TCP

    Have you tried to put into the 3rd parameter of the socket() call IPPROTO_TCP?
    my understanding is that SOCK_STREAM is for TCP. 0 is just default right?

  7. #7
    Registered User
    Join Date
    Oct 2013
    Posts
    15
    Quote Originally Posted by c99tutorial View Post
    ping does not verify that a particular port is open. The question is whether you can in fact make a connection using port 1234 from your client to your server
    I cannot make connection. I run my server first and later client. At that time client program prompt that cannot connect. so that's y

  8. #8
    Registered User
    Join Date
    Oct 2013
    Posts
    15
    I used teraterm to check whether the port is ok or not. But it showed connection refused...

  9. #9
    Registered User
    Join Date
    Oct 2013
    Posts
    15
    Quote Originally Posted by c99tutorial View Post
    ping does not verify that a particular port is open. The question is whether you can in fact make a connection using port 1234 from your client to your server

    I used telent now. I type telnet myclientip 1234 . it showed that connecting to myclientip.. could not open to the host, on port 1234: Connect failed.. means I cannot use that port no.. ???

  10. #10
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Is server running on windows? check windows firewall settings
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  11. #11
    Stoned Witch Barney McGrew's Avatar
    Join Date
    Oct 2012
    Location
    astaylea
    Posts
    420
    Firstly, gethostbyname is considered obsolete by POSIX, so you might use getaddrinfo instead. But neither are really needed by your program so you can get rid of gethostbyname, along with the call to gethostname.

    Your problem is with the call to connect -- some of the fields used by serv_addr are uninitialised in your call and sin_family should be assigned AF_INET. Call memset(&serv_addr, 0, sizeof serv_addr) before assigning to any of the fields.

    Also, for the call to socket, though not the call to connect, it may be necessary to check that the return value is equal to -1, rather than less than 0. I'm not sure, but I think you can have file descriptors with negative values.
    Last edited by Barney McGrew; 10-29-2013 at 04:54 AM.

  12. #12
    Registered User
    Join Date
    Oct 2013
    Posts
    15
    Quote Originally Posted by vart View Post
    Is server running on windows? check windows firewall settings
    Hi thanks for your answer. I had checked my firewall settings. It was off.

  13. #13
    Registered User
    Join Date
    Oct 2013
    Posts
    15
    Quote Originally Posted by Barney McGrew View Post
    Firstly, gethostbyname is considered obsolete by POSIX, so you might use getaddrinfo instead. But neither are really needed by your program so you can get rid of gethostbyname, along with the call to gethostname.

    Your problem is with the call to connect -- some of the fields used by serv_addr are uninitialised in your call and sin_family should be assigned AF_INET. Call memset(&serv_addr, 0, sizeof serv_addr) before assigning to any of the fields.

    Also, for the call to socket, though not the call to connect, it may be necessary to check that the return value is equal to -1, rather than less than 0. I'm not sure, but I think you can have file descriptors with negative values.
    Hi thanks for your answer. Now I changed my program a little bit. I just wanna test whether it can connect or not.
    my program is
    Code:
    #include
    <sys/socket.h>//for socket(), connect(), sendto() and recvform()
    
    #include
    <sys/types.h>
    
    #include
    <netinet/in.h>
    
    #include
    <netdb.h>
    
    #include
    <stdio.h>// for printf() and fprintf()
    
    #include
    <string.h>//for memset()
    
    #include
    <stdlib.h>//for atoi() and exit()
    
    #include
    <unistd.h>//for close()
    
    #include
    <errno.h>
    
    #include
    <arpa/inet.h>//for sockaddr_in and inet_addr()
    
     
    
    
    #define
     SERVERPORT 1234	
    
    
    int
     main(void)
    
    {
    
    	
    int sockfd =0;
    
    	
    struct sockaddr_in serv_addr;
    
    	
    if((sockfd=socket(AF_INET, SOCK_STREAM, 0)) < 0)
    
    	{
    
    		printf(
    "Cannot Connect\n");
    
    		
    return 1;
    
    	
    else
    
    		printf(
    "Connected\n");
    
    	}
    
    }
    
    
    but still cannot connect

  14. #14
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    > printf("Cannot Connect\n");
    Perhaps replacing printf() with perror() will shed enlightenment on to the REASON for the failure, as opposed to the ultimate shoulder shrug "it didn't work" you have at the moment.
    perror
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  15. #15
    Registered User
    Join Date
    Oct 2013
    Posts
    15
    Quote Originally Posted by Salem View Post
    > printf("Cannot Connect\n");
    Perhaps replacing printf() with perror() will shed enlightenment on to the REASON for the failure, as opposed to the ultimate shoulder shrug "it didn't work" you have at the moment.
    perror
    Hi I am using perror as you said. I started to run my server program from window and run client program in Linux. At that time, the terminal showed Cannot connect : connection refused. Why is it so?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Socket wont connect
    By Matty_Alan in forum Networking/Device Communication
    Replies: 2
    Last Post: 04-10-2010, 01:22 AM
  2. Using a single socket for accept() as well as connect()?
    By nkhambal in forum Networking/Device Communication
    Replies: 3
    Last Post: 10-20-2005, 05:43 AM
  3. My socket attempt refuses to connect
    By kzar in forum C Programming
    Replies: 3
    Last Post: 06-01-2005, 04:15 AM
  4. socket connect returning odd
    By WaterNut in forum C++ Programming
    Replies: 5
    Last Post: 05-10-2005, 08:49 PM
  5. need connect SQL through a DLL programming in c++
    By cmcortinas in forum C++ Programming
    Replies: 2
    Last Post: 01-29-2003, 11:57 AM

Tags for this Thread