dbgif_netcomm.c 2.64 KB

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <netinet/in.h>
#ifdef __sgi__
#include <bstring.h>
#endif

#include "dbgif.h"

int stSetupTCPconnection(int port)
{
    int sock;
    struct sockaddr_in sin;
    int optlen, optval;

    if ((sock = socket (AF_INET, SOCK_STREAM, 0)) < 0) {
        perror2 ("socket");
    }

    optval = 1;
    setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
    optval = 0;
    setsockopt (sock, SOL_SOCKET, SO_LINGER, &optval, sizeof(optval));

#if 0
    optlen = sizeof(optval);
    getsockopt (sock, SOL_SOCKET, SO_REUSEADDR, &optval, &optlen);
    printf("tvpcs opt reuseaddr %d len %d\n", optval, optlen);
    optlen = sizeof(optval);
    getsockopt (sock, SOL_SOCKET, SO_LINGER, &optval, &optlen);
    printf("tvpcs opt linger %d len %d\n", optval, optlen);
#endif

    sin.sin_addr.s_addr = INADDR_ANY;
    sin.sin_port = port;
    sin.sin_family = AF_INET;
    if (bind (sock, (struct sockaddr *)&sin, sizeof (sin)) < 0) {
        perror2 ("bind");
    }
    listen (sock, 5);
    printf("dbgif: Waiting for remote connection...\n");
    return (sock);
}

int netRead(int sock, char *buf, int len)
{
    unsigned char *cp, c;
    int n, i, *p;
    unsigned int amount, bytes_remain;
    KKHeader *event;
    int recvd = 0;
    int amount_done;

    bzero(buf, len);
    n = 0;
    while (n < 8) {
        n = recv(sock, buf, len, MSG_PEEK);
        if (n < 0) {
	    perror("dbgif: netRead: rcv");
	    break;
        }
        if (n == 0) {
            return (0);
        }
    }

    event = (KKHeader *)buf;
    
    bytes_remain = event->length;
    i = 0;
    while (bytes_remain) {
	amount = recv (sock, &buf[i], bytes_remain, 0);
	if (amount < 0)
	    perror ("netRead recv failed: ");
	bytes_remain -= amount;
	i += amount;
    }

    amount_done = n = i;
    if (verbose) {
        printf("%s: read block, size=%d - tcp\r\n    ", progName, n);
        flushPrintBuf();
    }
    if ((verbose || fp) && (event->code != _KK_REQ_GETFRAME)) {
	p = (int *)buf;
	n = (n+3) / 4; 			/* round up to words */
	for (i = 0; i < n; i++) {
            if (fp)
                fprintf(fp, "buf[%d] = 0x%x\n", i, *p);
	    if (verbose) {
	        printf("%08x ", *p);
		if ((i & 7) == 7)
		    printf("\r\n%s", (i+1) < n ? "    " : "");
	    }
	    p++;
        }
        if (verbose) {
	    if (((i-1) & 7) != 7)
		printf("\r\n");
	}
        flushPrintBuf();
    }

    if (amount_done < event->length) {
	if (fp)
	    fprintf (fp,"Received incomplete event: code = %d, expected = %d bytes, received %d\n", event->code, event->length, n);
    }

    return (amount_done);
}