LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Connection refused problem (http://www.linuxquestions.org/questions/programming-9/connection-refused-problem-4175438105/)

daedlock 11-21-2012 06:49 AM

Connection refused problem
 
I am trying to connect a port which has been listenning. I checked with netstat -tan and saw
tcp 0 0 0.0.0.0:2000 0.0.0.0:* LISTEN
There is no firewall. My code is a standart code :

memset(&addr,0,sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
addr.sin_port = htons(2000);

if ((sockfd = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP)) <0)
printf("ERROR opening socket\n");
strcpy(buffer,"hello world\r\n");
printf("port=%d-%d",ntohs(addr.sin_port),addr.sin_port);
if (connect(sockfd,(struct sockaddr *)&addr,sizeof(addr)) < 0)
printf("con failed %s",strerror(errno));

It gives the error "Connection Refused".
I looked at the wireshark log and saw that it is trying to connect any other port that is not been listenning. I can connect to the port with telnet.
What is wrong with this code?

theNbomr 11-21-2012 05:17 PM

If you cannot connect with a known-good client (I prefer netcat, 'nc' for testing such cases), it may be that the server is not accepting connections from localhost. What is the nature of the server?

I tried your code with nc listening as a server on port 2000, and it connected was was able to write to the server.

--- rod.

daedlock 11-22-2012 04:02 AM

I found out that it is endian problem htons,htonl functions don't work. I tried manually and it works. The server accepts connections from localhost becaues there is any other clients connecting that way.
But i could not find out why htons/htonl functions don't work.


All times are GMT -5. The time now is 12:21 AM.