User Guide

AXIS 2490 User’s Manual Examples
39
Simple TCP Client Program Example for a Generic TCP/IP port
This example is for use on Linux and other UNIX variants.
Note: The example provided here is intended only as a guideline for developing your own application
and there is NO
guarantee that the code will work in your particular application. All of the code
shown here is subject to change without prior notice.
* This uses blocking sockets without select(),
use select() for more complex applications.
* Compile with: gcc -Wall tcpclient.c -o
tcpclient
* Axis Communications AB, Lund Sweden
*/
#include <string.h>
#include <unistd.h> /* read, write, close */
#include <stdlib.h>
#include <stdio.h>
#include <netinet/in.h> /* sockaddr_in,
IPPROTO_TCP */
#include <netdb.h> /* gethostbyname */
#include <errno.h> /* errno etc. */
#define RXBUFSIZE 1000
/* Create TCP connection to host:portnr, return
filedescriptor > 0 if ok */
int client_connect(const char* host, u_short
portnr)
{
ints=0;
struct sockaddr_in server;
struct hostent *hp;
hp = gethostbyname(host);
if (hp != NULL) {
bzero((char *) &server, sizeof server);
bcopy(hp->h_addr, (char *) &server.sin_addr,
hp->h_length);
server.sin_family = hp->h_addrtype; /*
Protocol family */
server.sin_port = htons(portnr);/* Port number
*/
s = socket(AF_INET, SOCK_STREAM, 0);
if(s<0){
printf("error in socket\n");
}
if (connect(s, (struct sockaddr *) & server,
sizeof server) < 0) {
printf("connect() error in bind\n");
s=0;
}
}
return s;
}
int main(int argc, char **argv)
{
int fd;
u_short portnr = 4000;
const char *host;
if (argc < 2) {
printf("Usage: tcpclient host [port]\n");
printf(" port is default 4000\n");
exit(1);
}
host = argv[1];
if (argc > 2) {
portnr = atoi(argv[2]);
}
printf("Connecting to %s:%u...\n", host,
portnr);
fd = client_connect(host, portnr);
if (fd > 0) {
int num_sent;
int num_rec;
char txstring[]="This is a test string\r\n";
int txlen = strlen(txstring);
char rx_buf[RXBUFSIZE];
intrx_tot=0;
printf("Connected ok\n");
/* We are connected */
num_sent = write(fd, txstring, txlen);
if (num_sent != txlen) {
perror("Failed to write all");
if (errno == EAGAIN)
{
/* We can send remaining bytes */
}
}
printf("Sent %i bytes: '%s'\n", num_sent,
txstring);
printf("Reading 30 bytes data...\n");
/* Read data until we got 30 bytes */
while (fd && rx_tot < 30) {
num_rec = read(fd, &rx_buf[rx_tot],
30-rx_tot);
if (num_rec > 0) {
/* Ok */
rx_tot += num_rec;
rx_buf[rx_tot]='\0';
printf("rx_tot: %i '%s'\n", rx_tot,
rx_buf);
}else{
perror("Failed to read\n");
if (errno != EAGAIN)
{
printf("Closing\n");
close(fd);
fd = -1;
}
}
}
if(fd>0){
close(fd);
}
} else {
perror("Failed to connect!\n");
}
return 0;
}
Continued.....