[國嵌攻略][092][UDP網絡程序設計]

server.csocket

#include <sys/socket.h>
#include <netinet/in.h>
#include <strings.h>
#include <stdio.h>

#define SERVER_PORT 3333

void main(){
    //建立標識
    int serverfd;
    
    serverfd = socket(AF_INET, SOCK_DGRAM, 0);   //創建UDP鏈接
    
    //綁定地址
    struct sockaddr_in serverAddr;
    
    serverAddr.sin_family = AF_INET;                   //設置協議
    serverAddr.sin_port = htons(SERVER_PORT);          //設置端口
    serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);    //設置地址
    bzero(serverAddr.sin_zero, 8);                     //設置爲零
    
    bind(serverfd, (struct sockaddr *)&serverAddr, sizeof(struct sockaddr));
    
    //接收數據
    char buffer[2048];
    struct sockaddr_in clientAddr;
    socklen_t clientAddrLen;
    
    clientAddrLen = sizeof(struct sockaddr);
    recvfrom(serverfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&clientAddr, &clientAddrLen);
    
    //顯示數據
    char *clientIPAddr;
    
    clientIPAddr = (char *)inet_ntoa(clientAddr.sin_addr.s_addr);
    printf("server recvice from %s:\n%s", clientIPAddr, buffer);
    
    //關閉鏈接
    close(serverfd);
}

 

client.cspa

#include <sys/socket.h>
#include <netinet/in.h>
#include <strings.h>
#include <stdio.h>

#define SERVER_PORT 3333

int main(int argc, char **argv){
    //參數檢查
    if(argc != 2){
        printf("Usage:\n\t%s <ip address>\n", argv[0]);
        return -1;
    }
    
    //建立標識
    int clientfd;
    
    clientfd = socket(AF_INET, SOCK_DGRAM, 0);   //創建UDP鏈接
    
    //輸入數據
    char buffer[2048];
    
    printf("client send to %s:\n", argv[1]);
    fgets(buffer, sizeof(buffer), stdin);
    
    //發送數據
    struct sockaddr_in serverAddr;
    
    serverAddr.sin_family = AF_INET;                   //設置協議
    serverAddr.sin_port = htons(SERVER_PORT);          //設置端口
    serverAddr.sin_addr.s_addr = inet_addr(argv[1]);   //設置地址
    bzero(serverAddr.sin_zero, 8);                     //設置爲零
    
    sendto(clientfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&serverAddr, sizeof(struct sockaddr));
    
    //關閉鏈接
    close(clientfd);
    
    return 0;
}
相關文章
相關標籤/搜索