#include <iostream>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
int main (int argc, char * const argv[]) {
std::cout << "hello world\n";
int myposixsocketnumber=socket(AF_INET,SOCK_STREAM,0);
std::cout << "myposixsocketnumber:" << myposixsocketnumber << "\n";
sockaddr_in mysockaddrin;
{
mysockaddrin.sin_family=AF_INET;
mysockaddrin.sin_addr.s_addr=inet_addr("192.168.1.38");
// mysockaddrin.sin_port=2162;
mysockaddrin.sin_port=80;
}
std::cout << "connect ip:" << mysockaddrin.sin_addr.s_addr << " port:" << mysockaddrin.sin_port << "\n";
int myresult=connect(myposixsocketnumber,(sockaddr*)&mysockaddrin,sizeof(mysockaddrin));
std::cout << "myresult:" << myresult << "\n";
if(myresult){
std::cout << "errno:" << errno << " strerror(errno):" << strerror(errno) << "\n";
}
char *mymessage="are_you_ok\n\n"; ssize_t mymessagelen=(size_t)strlen(mymessage);
ssize_t mylenwritten=write(myposixsocketnumber,mymessage,mymessagelen);
std::cout << "mylenwritten:" << mylenwritten << "\n";
return 0;
}
perry-mb:~/sockettest za$ g++ main.cpp
perry-mb:~/sockettest za$ ./a.out
hello world
myposixsocketnumber:3
connect ip:637642944 port:80
myresult:-1
errno:61 strerror(errno):Connection refused
Broken pipe
perry-mb:~/sockettest za$
perry-mb:~/sockettest za$ telnet 192.168.1.38 80
Trying 192.168.1.38...
Connected to 192.168.1.38.
Escape character is '^]'.
hello
Connection closed by foreign host.
perry-mb:~/sockettest za$