Author Topic: sockets programming: What's wrong with my code  (Read 2842 times)

0 Members and 6 Guests are viewing this topic.

Offline PsychoRebellious

  • Peasant
  • *
  • Posts: 130
  • Cookies: -6
    • View Profile
    • My Rantings
sockets programming: What's wrong with my code
« on: March 07, 2015, 12:53:41 pm »
sox.cpp
Code: (cpp) [Select]
//sockets
#include <cstring>
#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <cstdlib>
#include <arpa/inet.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
//server id it will only be receiving code from the client

int sockfd,incomingfd;
sockaddr_in serveraddr;
sockaddr_in clientaddr;
sockfd=socket(AF_INET,SOCK_STREAM,0);//scoekt

  bzero((char *) &serveraddr, sizeof(serveraddr));//set to zero

//for storing sent/received message
char message[256];
message[0]='x';

//set serveraddr
serveraddr.sin_family=AF_INET;
serveraddr.sin_port=htons(2500);
serveraddr.sin_addr.s_addr=INADDR_ANY;//let the OS manage this other wise the nodes addrr
//ok

//bind the socket to the server address
int status=bind(sockfd,(sockaddr *) &serveraddr,sizeof(serveraddr));
if(status<0){
std::cout<<"OOPS FAILED TO BIND";exit;}

else std::cout<<"Server is alive\n";
//end of condition

std::cout<<"Awaiting for incoming connections\n";
listen(sockfd,5);

socklen_t client_len=sizeof(clientaddr);//get socket length

if(incomingfd=accept(sockfd,(sockaddr*)&clientaddr,&client_len)>0){
std::cout<<"connection made to a device\n";}//end of if

if(incomingfd>0){
while(1==1){
bzero(message,256);
int n=read(incomingfd,message,255);
if(n<0)std::cout<<"Fail to read\n";
std::cout<<"user says "<<message<<std::endl;

}//the infinte input reading loop


}//end of if

std::cin.get();
return 0;
}


user.cpp
Code: (cpp) [Select]
#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <cstdlib>
#include <cstring>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(){

sockaddr_in host;
  bzero((char *) &host, sizeof(host));
int hostfd;
int sockfd;
int port=2500;
char message[256];
//create a socket
sockfd=socket(AF_INET,SOCK_STREAM,0);

//initialize host
host.sin_family=AF_INET;
host.sin_port=htons(port);
host.sin_addr.s_addr=inet_addr("192.168.0.103");

//connect to host
std::cout<<"Connecting to host 192.168.0.3"<<std::endl;
if(connect(sockfd,(sockaddr*)&host,sizeof(host))<0){std::cout<<"Failed to connect\n";exit;}

else{
std::cout<<"Connected to the host successfully\n";

while(true)

{
std::cout<<"Enter your message to send to the server\n";
bzero(message,256);
std::cin>>message;
std::cout<<"Okay sending messaging to the server\n";
int n=write(sockfd,message,strlen(message));
if(n<0){std::cout<<"Error writing ";exit;}
else std::cout<<"Your message is sent \n";



}//end of while body


}//heres the main loop for keep sending messages lel





std::cin.get();
return 0;

}

I am trying to have one end(user) send messages and other end(server) reading them and just writing them down. The user.cpp is working fine it keeps asking you to enter a message after establishing a connection.
The server.cpp works fine too to the point of establishing connection (it tells the connection is made once you run user.exe / user.o) but it won't write the received message to console. i am sure it is receiving the messages because it would've generated an error other wise because of the line
Code: [Select]
if(n<0)std::cout<<"Fail to read\n"; But it's not, it just keeps wiating and wiating and prints no message ;/ i don't have C background so I could've fucked up somewhere
« Last Edit: March 07, 2015, 05:50:42 pm by PsychoRebellious »

Offline flowjob

  • Knight
  • **
  • Posts: 327
  • Cookies: 46
  • Pastafarian
    • View Profile
Re: sockets programming: What's wrong with my code
« Reply #1 on: March 07, 2015, 05:59:17 pm »
Your code is fucking horrible. I am amazed that it even compiled. Eg the line that doesnt work:
Code: (C++) [Select]
if(n<0)std::cout<<"Fail to read\n";
std::cout<<"user says "<<message<<std::endl;
NEVER use if-else without curly brackets {}, it is far more verbose and bugs are less likely to be written if you use them.
In the above code the message would be outputted even if it failed to read (no else-block).
Properly formatted these lines would look like this:
Code: (C++) [Select]
if (n < 0) {
    std::cout << "Fail to read" << std::endl;
    }
else {
    std::cout << "user says " << message << std::endl;
    }

Also, make use of whitespace and indentation to make your code easier to read and understand!

I didn't check for other things, as I'm not really familiar with the libraries you used, but i bet another member is, and will look for other bugs...
Quote
<phil> I'm gonna DDOS the washing machine with clothes packets.
<deviant_sheep> dont use too much soap or youll cause a bubble overflow

Offline PsychoRebellious

  • Peasant
  • *
  • Posts: 130
  • Cookies: -6
    • View Profile
    • My Rantings
Re: sockets programming: What's wrong with my code
« Reply #2 on: March 07, 2015, 06:26:38 pm »
Your code is fucking horrible. I am amazed that it even compiled. Eg the line that doesnt work:
Code: (C++) [Select]
if(n<0)std::cout<<"Fail to read\n";
std::cout<<"user says "<<message<<std::endl;
NEVER use if-else without curly brackets {}, it is far more verbose and bugs are less likely to be written if you use them.
In the above code the message would be outputted even if it failed to read (no else-block).
Properly formatted these lines would look like this:
Code: (C++) [Select]
if (n < 0) {
    std::cout << "Fail to read" << std::endl;
    }
else {
    std::cout << "user says " << message << std::endl;
    }

Also, make use of whitespace and indentation to make your code easier to read and understand!

I didn't check for other things, as I'm not really familiar with the libraries you used, but i bet another member is, and will look for other bugs...

For single line conditional statement, curly braces are not recommended, but I agree i should've added an exit; on condition. But that's not the problem here

Offline flowjob

  • Knight
  • **
  • Posts: 327
  • Cookies: 46
  • Pastafarian
    • View Profile
Re: sockets programming: What's wrong with my code
« Reply #3 on: March 07, 2015, 06:44:38 pm »
For single line conditional statement, curly braces are not recommended, but I agree i should've added an exit; on condition. But that's not the problem here

Curly brackets are ALWAYS recommended, as they add verbosity and minimize the risk of bugs.

Also, have you tried hitting Return after running the server? Because, maybe a connection couldn't be stablished, and "std::cin.get()" waits for user input. Also, you should have an if/else for every possible error that could occur, and print a error message in that case. Your code doesn't print an error message if accepting a connection didn't work. It just ignores the infinite loop and waits for user input at the end of your program with "std::cin.get()".

EDIT:
I also just saw you checked twice if a connection could be stablished, but never have an else printing a error message if it fails. One check is enough.
And please post the program input and output, it could help finding the source of the problem.
« Last Edit: March 07, 2015, 06:48:56 pm by flowjob »
Quote
<phil> I'm gonna DDOS the washing machine with clothes packets.
<deviant_sheep> dont use too much soap or youll cause a bubble overflow

Offline KryDos

  • Serf
  • *
  • Posts: 42
  • Cookies: 8
  • Software Engineer, Emacs uesr
    • View Profile
Re: sockets programming: What's wrong with my code
« Reply #4 on: March 07, 2015, 07:01:10 pm »
Curly brackets are ALWAYS recommended, as they add verbosity and minimize the risk of bugs.

Also, have you tried hitting Return after running the server? Because, maybe a connection couldn't be stablished, and "std::cin.get()" waits for user input. Also, you should have an if/else for every possible error that could occur, and print a error message in that case. Your code doesn't print an error message if accepting a connection didn't work. It just ignores the infinite loop and waits for user input at the end of your program with "std::cin.get()".

EDIT:
I also just saw you checked twice if a connection could be stablished, but never have an else printing a error message if it fails. One check is enough.
And please post the program input and output, it could help finding the source of the problem.

The problem is not there. The issue in read(). It blocks loop and don't read anything although I'm sending data to the server.

I have no big C experience maybe you know why read() do not receive anything?
« Last Edit: March 07, 2015, 07:01:42 pm by KryDos »

Offline flowjob

  • Knight
  • **
  • Posts: 327
  • Cookies: 46
  • Pastafarian
    • View Profile
Re: sockets programming: What's wrong with my code
« Reply #5 on: March 07, 2015, 07:19:19 pm »
The problem is not there. The issue in read(). It blocks loop and don't read anything although I'm sending data to the server.

I have no big C experience maybe you know why read() do not receive anything?

Could you explain why you think that read() is the problem here? Maybe I'm missing something.
The read command itself seems ok (tho I have no experience using these libs/commands, just looking at tutorials and specifications).
That's why I'd like to see what exactly he entered into the program (connection details,etc), and what the program printed. Maybe there's something wrong with the connection details (eg connection over the internet without port-forwarding to the server).
Quote
<phil> I'm gonna DDOS the washing machine with clothes packets.
<deviant_sheep> dont use too much soap or youll cause a bubble overflow

Offline KryDos

  • Serf
  • *
  • Posts: 42
  • Cookies: 8
  • Software Engineer, Emacs uesr
    • View Profile
Re: sockets programming: What's wrong with my code
« Reply #6 on: March 07, 2015, 07:23:39 pm »
Could you explain why you think that read() is the problem here?
I compiled sox.cpp. Added some debug output and executed it. Before read() all works (it's accepting only one connection but anyway, it works). When I'm trying to send something to the server read() is still waiting for the data.

I didn't compile user.cpp (which is socket client) but I'm using nc (netcat) instead.
« Last Edit: March 07, 2015, 07:24:44 pm by KryDos »

Offline flowjob

  • Knight
  • **
  • Posts: 327
  • Cookies: 46
  • Pastafarian
    • View Profile
Re: sockets programming: What's wrong with my code
« Reply #7 on: March 07, 2015, 07:32:12 pm »
Ok, I compiled and debugged it, the message is received, but not printed. the program continues after the read() command.
Going to continue debugging after dinner.
Quote
<phil> I'm gonna DDOS the washing machine with clothes packets.
<deviant_sheep> dont use too much soap or youll cause a bubble overflow

Offline KryDos

  • Serf
  • *
  • Posts: 42
  • Cookies: 8
  • Software Engineer, Emacs uesr
    • View Profile
Re: sockets programming: What's wrong with my code
« Reply #8 on: March 07, 2015, 07:33:52 pm »
Ok, I compiled and debugged it, the message is received, but not printed. the program continues after the read() command.
Going to continue debugging after dinner.

Hm, strange. I even didn't get any message. It's not printed but it even not executes next line after read() (I have added debug line next to the read() line).

Offline PsychoRebellious

  • Peasant
  • *
  • Posts: 130
  • Cookies: -6
    • View Profile
    • My Rantings
Re: sockets programming: What's wrong with my code
« Reply #9 on: March 07, 2015, 07:35:53 pm »
Fixed, and working like a charm. Xires helped me out over IRc.
Code: (cpp) [Select]
  std::cout << "Enter your message to send to the server" << std::endl;

            bzero(message, 256);

            std::cin.getline(message, 256);//this line is the problem
//changing to getline from cin>>message solved it, embarrassing I know


Offline KryDos

  • Serf
  • *
  • Posts: 42
  • Cookies: 8
  • Software Engineer, Emacs uesr
    • View Profile
Re: sockets programming: What's wrong with my code
« Reply #10 on: March 07, 2015, 07:37:13 pm »
Congrats. Just fixed it too but I just removed all warnings and now your code is working for me, even with read() function.

Offline PsychoRebellious

  • Peasant
  • *
  • Posts: 130
  • Cookies: -6
    • View Profile
    • My Rantings
Re: sockets programming: What's wrong with my code
« Reply #11 on: March 07, 2015, 07:41:18 pm »
Congrats. Just fixed it too but I just removed all warnings and now your code is working for me, even with read() function.

The read() function wasn't really causing any trouble, except for failing to read the characters. Thank you, all for your help, and taking the trouble. Much appreciated. I'll go improve the code like flowjob suggested and make the server respond back ( p2p chat)
One thing that confused me was that the sever would wait for the end user to press enter and then print
"user says "

Offline KryDos

  • Serf
  • *
  • Posts: 42
  • Cookies: 8
  • Software Engineer, Emacs uesr
    • View Profile
Re: sockets programming: What's wrong with my code
« Reply #12 on: March 07, 2015, 07:45:49 pm »
You want to create p2p chat just for fun?

Because you already can use netcat :) it allows you to create server and client.

Offline PsychoRebellious

  • Peasant
  • *
  • Posts: 130
  • Cookies: -6
    • View Profile
    • My Rantings
Re: sockets programming: What's wrong with my code
« Reply #13 on: March 07, 2015, 08:03:12 pm »
I was coding it just for the heck of it. For fun and studying  :-X

Offline ArkPhaze

  • Peasant
  • *
  • Posts: 136
  • Cookies: 20
  • null terminated
    • View Profile
Re: sockets programming: What's wrong with my code
« Reply #14 on: March 08, 2015, 08:44:34 am »
Curly brackets are ALWAYS recommended, as they add verbosity and minimize the risk of bugs.

Also, have you tried hitting Return after running the server? Because, maybe a connection couldn't be stablished, and "std::cin.get()" waits for user input. Also, you should have an if/else for every possible error that could occur, and print a error message in that case. Your code doesn't print an error message if accepting a connection didn't work. It just ignores the infinite loop and waits for user input at the end of your program with "std::cin.get()".

EDIT:
I also just saw you checked twice if a connection could be stablished, but never have an else printing a error message if it fails. One check is enough.
And please post the program input and output, it could help finding the source of the problem.

They don't add any verbosity, the definition in which you place 'verbosity' in here, is far out of context. The only thing it does is add more lines to define what is already as verbose as it can get. There's no issues if the code is properly formatted/indented, and most modern text editors, if you're not using a full blown IDE will do this by default with smart indenting features.

Otherwise, problems are also less likely to exist if you remove the noun usually referred to with PEBCAK. ;) But that doesn't mean it's a very good solution to an existing problem now does it?
« Last Edit: March 08, 2015, 08:51:46 am by ArkPhaze »
sig=: ArkPhaze

[ J/ASM/.NET/C/C++ - Software Engineer ]