简体   繁体   中英

Socket programming in Linux by C++

I am developing a C++ app in openSUSE 12.3 and one of it's part is responsible to send data to a device via Socket (in LAN). I am using this code

int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *printer;    
portno = 9100;  

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0) error("ERROR opening socket\n"); 
printer = gethostbyname("100.0.69.23");
if(printer == NULL) error("No such device on 100.0.69.23\n");
//set bit set to zero
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *) printer->h_addr, (char *) &serv_addr.sin_addr.s_addr, printer-     >h_length);

serv_addr.sin_port = htons(portno); 

if(connect(sockfd, (struct sockaddr *) & serv_addr, sizeof(serv_addr)) < 0) 
    {error("ERROR connecting");
           return;
     }

n = write(sockfd, data, datalenght);
if(n < 0) error("ERROR sending command to printer");
n = read(sockfd, buffer, 200);

I think the code is correct but the connect function returns -1 and seems that could not connect to the device (printer) . This code was written in openSUSE 11 and was working OK and I could send/receive data to device but when I copy/paste it to new system (openSUSE 12.3) it gives me failure in connecting. I ping result on the specific IP which is in use show that device is reachable via LAN

I think you should consider the possibility that hostent returned by gethostbyname function might have AF_INET6 address family (in which case it will be IPv6 instead of IPv4 address).

http://linux.die.net/man/3/gethostbyname

So you can either use GNU extension function gethostbyname2 function that will allow you to specify address family.

printer = gethostbyname2("100.0.69.23", AF_INET);

Or instead you can use getaddrinfo function, as gethostbyname function is said to be obsolete, by the documentation.

As already mentioned, you are checking for printer == NULL before initializing it. I think you meant the following instead:

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) error("ERROR opening socket\n");
printer = gethostbyname("100.0.69.23");
...

Also the structure of the code seems to indicate that when you want to send a command to the printer you connect() , write() then read() , which is OK if you are only ever sending one command, but suboptimal if you are sending multiple commands. In the latter case you want to separate the connect() from the write() as it's fairly expensive to connect so you want to do it just once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM