File: tcppollclient.c

package info (click to toggle)
o2 1.0~repack-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 1,156 kB
  • sloc: ansic: 9,132; python: 137; sh: 111; makefile: 10
file content (87 lines) | stat: -rw-r--r-- 2,126 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/* udp-broadcast-client.c
 * udp datagram client
 * Get datagram stock market quotes from UDP broadcast:
 * see below the step by step explanation
 */

#ifdef WIN32
#include <winsock2.h> 
#include <windows.h> 
#else
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <time.h>
#include <signal.h>


#ifndef TRUE
#define TRUE 1
#define FALSE 0
#endif


/*
 * This function reports the error and
 * exits back to the shell:
 */
static void
displayError(const char *on_what) {
    fputs(strerror(errno),stderr);
    fputs(": ",stderr);
    fputs(on_what,stderr);
    fputc('\n',stderr);
    exit(1);
}

int main(int argc,char **argv)
{
    FILE *inf = fopen("port.dat", "r");
    if (!inf) displayError("Could not find port.dat");
    char ip[100];
    int tcp_port;
    if (fscanf(inf, "%s %d", ip, &tcp_port) != 2) {
        displayError("could not scanf");
    }
//    strcpy(ip, "localhost");
//    printf("ip %s tcp %d\n", ip, tcp_port);
    fclose(inf);
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == -1) {
        displayError("tcp socket set up error");
    }
    struct sockaddr_in remote_addr;
    // set up the connection
    memset(&remote_addr, 0, sizeof(struct sockaddr_in));
    remote_addr.sin_family = AF_INET;      //AF_INET means using IPv4
//    inet_pton(AF_INET, ip, &(remote_addr.sin_addr));
    struct hostent *hostp = gethostbyname(ip);
    if (!hostp) displayError("gethostbyname failed");
    memcpy(&remote_addr.sin_addr, hostp->h_addr, sizeof(remote_addr.sin_addr));
//
    remote_addr.sin_port = htons(tcp_port);
    printf("*** connecting to %s:%d\n", ip, tcp_port);
    if (connect(sock, (struct sockaddr *) &remote_addr, sizeof(remote_addr)) < 0) {
        displayError("Connect Error!");
    }
    while (TRUE) {
        char *msg = "This is a test\n";
        if (write(sock, msg, strlen(msg) + 1) < 0) {
            displayError("send");
        }
#ifdef WIN32
		Sleep(4);
#else
		sleep(4)
#endif
    }
    return 0;
}