#include #include #include #include #include #include #include #include #include struct UdpHeader { u_short src_port; u_short targ_port; u_short length; u_short checksum; }; char message[] = "Hello there!\n"; char msgbuf[1024]; int main(int argc, char *argv[]) { int sock; unsigned int length; // размер структуры адреса struct sockaddr_in addr; struct UdpHeader header; struct hostent *hp; // структура хоста if (argc != 3) { printf("Usage: server port\n"); exit(-1); } sock = socket(AF_INET, SOCK_RAW, IPPROTO_UDP); if(sock < 0) { perror("Cant open socket"); exit(-2); } addr.sin_family = AF_INET; //addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); hp = gethostbyname(argv[1]); // извлечение хоста if (hp==0) { perror("Unknown host"); exit(-3); } bcopy((char *)hp->h_addr, (char *)&addr.sin_addr, hp->h_length); //addr.sin_port = htons(atoi(argv[2])); // извлечение порта length=sizeof(struct sockaddr_in); header.targ_port = htons(atoi(argv[2])); header.length = htons(sizeof(header)+sizeof(message)); header.checksum = 0; memcpy((void *)msgbuf, (void *)&header, sizeof(header)); memcpy((void *)(msgbuf+sizeof(header)), (void *)message, sizeof(message)); sendto(sock, msgbuf, sizeof(header)+sizeof(message), 0, (struct sockaddr *)&addr, sizeof(addr)); close(sock); return 0; }