#include <stdio.h>
#include <winsock.h>

#define MAXBUF 512
char buf[MAXBUF];

int main(int argc, char* argv[])
{
    WSADATA data;
    SOCKET sock;
    struct sockaddr_in addr;
    int i, len, fromlen;

    if (argc != 2) {
        printf("usage: wudp <IP address>\n");
        exit(1);
    }

    /* initialize windows socket */
    WSAStartup(0x0101, &data);

    /* Create socket */
    if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) {
        fprintf(stderr, "Error socket(): %d\n", WSAGetLastError());
        exit(1);
    }

    /* initialize the parameter */
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(3289);
    addr.sin_addr.s_addr = inet_addr(argv[1]);

    /* make a packet (PRINTER STATUS) */
    buf[0] = 'E';
    buf[1] = 'P';
    buf[2] = 'S';
    buf[3] = 'O';
    buf[4] = 'N';
    buf[5] = 'Q'; // PacketType(Q)
    buf[6] = 0x03; // DeviceType(3)
    buf[7] = 0x00; // DeviceNumber(0)
    buf[8] = 0x00; // Function(0010h)
    buf[9] = 0x10;
    
    buf[10] = 0x00; // Result
    buf[11] = 0x00;
    buf[12] = 0x00; // Parameter length
    buf[13] = 0x00;

    /* send a packet */
    i = sendto(sock, buf, 14, 0, (struct sockaddr*)&addr, sizeof(addr));

    /* receive packet */
    fromlen = sizeof(addr);
    len = recvfrom(sock, buf, MAXBUF, 0, (struct sockaddr*)&addr, &fromlen);

    /* print receive packet */
    if (len) {
        if ((buf[10] == 0x00) && (buf[11] == 0x00))
            for (i = 0; i < len; i++)
                printf("%3d:%02Xh\n", i, buf[i] & 0xff);
    }

    /* close socket */
    closesocket(sock);
    return 0;
}