Socket tips: UDP Echo service – Server code

Socket tips: UDP Echo service – Server code

大家好,又见面了,我是全栈君,祝每个程序员都可以多学几门语言。

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>

#define BUFFER_LENGTH 1024

void ReverseMessage(char buffer[], ssize_t receivedBytesCount);

void ExitWithMessage(const int errorCode, const char * errorMessage)
{
    fprintf(stderr, "\n\nError Msg  : %s\n", errorMessage);
    fprintf(stderr, "Error Code : 0x%X\n", errorCode);
    fprintf(stderr, "Location   : %s: %d\n\n", __FILE__, __LINE__);

    exit(errorCode);
}

void PrintIPv4(unsigned long ipvalue, FILE * stream)
{
    uint8_t a;
    uint8_t b;
    uint8_t c;
    uint8_t d;

    a = ipvalue >> 24;

    ipvalue -= a * 0x01000000;
    b = ipvalue >> 16;

    ipvalue -= b * 0x00010000;
    c = ipvalue >> 8;

    ipvalue -= c * 0100000100;
    d = ipvalue;

    fprintf(stream, "%d.%d.%d.%d", d, c, b, a);
}

void PrintSocketAddress(const struct sockaddr * address, FILE * stream)
{
    struct in_addr ip4addr;
    in_port_t port;

    struct sockaddr_in * ipv4Address;

    if(address == NULL || stream == NULL)
    {
        return;
    }

    //printf("sa_family: %d\n", address->sa_family);

    switch(address->sa_family)
    {
        case AF_INET:

            fputs("[IPv4] ", stream);

            ipv4Address = (struct sockaddr_in *)address;
            ip4addr = ipv4Address->sin_addr;

            port = ntohs(ipv4Address->sin_port);

            //fprintf(stream, "ip4addr.s_addr: %X\n", ip4addr.s_addr);
            PrintIPv4(ip4addr.s_addr, stream);
            fprintf(stream, " : %d", port);

            break;
        case AF_INET6:

            fputs("[IPv6] ", stream);

            break;
        default:
            fputs("[unknown type]", stream);
            return;
    }
}

void PrintTime(FILE * stream)
{
    time_t currentTime;
    struct tm * local_time;
    struct timeval tv;

    currentTime = time(0);
    local_time = localtime(¤tTime);
    gettimeofday(&tv);

    fprintf(stream, "%04d-%02d-%02d %02d:%02d:%02d.%03d",
            local_time->tm_year + 1900,
            local_time->tm_mon + 1,
            local_time->tm_mday,
            local_time->tm_hour,
            local_time->tm_min,
            local_time->tm_sec,
            tv.tv_usec / 1000);

}

int main(int argc, char * argv[])
{
    char * serverPortString;
    struct addrinfo addrCriteria;
    struct addrinfo *serverAddr;
    int socketHandle;
    int returnValue;

    struct sockaddr_storage clientAddr;
    socklen_t clientAddrLen = sizeof(struct sockaddr);
    char buffer[BUFFER_LENGTH];
    ssize_t receivedBytesCount;
    ssize_t sendBytesCount;

    if(argc != 2)
    {
        //ExitWithMessage(0xF001, "Need parameter: <Server_Port>");
        serverPortString = "2001";
    }
    else
    {
        // First argument: local port
        serverPortString = argv[1];
    }

    memset(&addrCriteria, 0, sizeof(struct addrinfo));

    addrCriteria.ai_family = AF_UNSPEC; // Any address family
    addrCriteria.ai_flags = AI_PASSIVE; // Accept on any address/port
    addrCriteria.ai_socktype = SOCK_DGRAM; // only datagram socket
    addrCriteria.ai_protocol = IPPROTO_UDP; // only UDP socket

    returnValue = getaddrinfo(NULL, serverPortString, &addrCriteria, &serverAddr);
    if(returnValue != 0)
    {
        fprintf(stderr, "getaddrinfo() failed.\n");
        ExitWithMessage(returnValue, gai_strerror(returnValue));
    }

    // Create socket for incomming connections
    socketHandle = socket(serverAddr->ai_family, serverAddr->ai_socktype, serverAddr->ai_protocol);
    if(socketHandle < 0)
    {
        fprintf(stderr, "socket() failed.\n");
        ExitWithMessage(socketHandle, gai_strerror(socketHandle));
    }

    // Bind to local address
    returnValue = bind(socketHandle, serverAddr->ai_addr, serverAddr->ai_addrlen);
    if(returnValue < 0)
    {
        fprintf(stderr, "bind() failed.\n");
        ExitWithMessage(returnValue, gai_strerror(returnValue));
    }

    // Free address list allocated by getaddrinfo
    freeaddrinfo(serverAddr);

    printf("Starting the UDP Server ...\n");
    printf("Listinning at port %s\n\n", serverPortString);

    while(1)
    {
        receivedBytesCount = recvfrom(
			socketHandle,
			buffer,
			BUFFER_LENGTH,
			0,
			(struct sockaddr *)&clientAddr,
			&clientAddrLen);

        // printf("Received %d bytes.\n", receivedBytesCount);

        if(receivedBytesCount < 0)
        {
            fprintf(stderr, "recvfrom() failed.\n");
            ExitWithMessage(receivedBytesCount, gai_strerror(receivedBytesCount));
        }

        fputs("Handling client ", stdout);
        PrintSocketAddress((struct sockaddr *)&clientAddr, stdout);

        fputs(" at ", stdout);
        PrintTime(stdout);

        fputc('\n', stdout);

        buffer[receivedBytesCount] = '
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <time.h> #define BUFFER_LENGTH 1024 void ReverseMessage(char buffer[], ssize_t receivedBytesCount); void ExitWithMessage(const int errorCode, const char * errorMessage) { fprintf(stderr, "\n\nError Msg : %s\n", errorMessage); fprintf(stderr, "Error Code : 0x%X\n", errorCode); fprintf(stderr, "Location : %s: %d\n\n", __FILE__, __LINE__); exit(errorCode); } void PrintIPv4(unsigned long ipvalue, FILE * stream) { uint8_t a; uint8_t b; uint8_t c; uint8_t d; a = ipvalue >> 24; ipvalue -= a * 0x01000000; b = ipvalue >> 16; ipvalue -= b * 0x00010000; c = ipvalue >> 8; ipvalue -= c * 0100000100; d = ipvalue; fprintf(stream, "%d.%d.%d.%d", d, c, b, a); } void PrintSocketAddress(const struct sockaddr * address, FILE * stream) { struct in_addr ip4addr; in_port_t port; struct sockaddr_in * ipv4Address; if(address == NULL || stream == NULL) { return; } //printf("sa_family: %d\n", address->sa_family); switch(address->sa_family) { case AF_INET: fputs("[IPv4] ", stream); ipv4Address = (struct sockaddr_in *)address; ip4addr = ipv4Address->sin_addr; port = ntohs(ipv4Address->sin_port); //fprintf(stream, "ip4addr.s_addr: %X\n", ip4addr.s_addr); PrintIPv4(ip4addr.s_addr, stream); fprintf(stream, " : %d", port); break; case AF_INET6: fputs("[IPv6] ", stream); break; default: fputs("[unknown type]", stream); return; } } void PrintTime(FILE * stream) { time_t currentTime; struct tm * local_time; struct timeval tv; currentTime = time(0); local_time = localtime(¤tTime); gettimeofday(&tv); fprintf(stream, "%04d-%02d-%02d %02d:%02d:%02d.%03d", local_time->tm_year + 1900, local_time->tm_mon + 1, local_time->tm_mday, local_time->tm_hour, local_time->tm_min, local_time->tm_sec, tv.tv_usec / 1000); } int main(int argc, char * argv[]) { char * serverPortString; struct addrinfo addrCriteria; struct addrinfo *serverAddr; int socketHandle; int returnValue; struct sockaddr_storage clientAddr; socklen_t clientAddrLen = sizeof(struct sockaddr); char buffer[BUFFER_LENGTH]; ssize_t receivedBytesCount; ssize_t sendBytesCount; if(argc != 2) { //ExitWithMessage(0xF001, "Need parameter: <Server_Port>"); serverPortString = "2001"; } else { // First argument: local port serverPortString = argv[1]; } memset(&addrCriteria, 0, sizeof(struct addrinfo)); addrCriteria.ai_family = AF_UNSPEC; // Any address family addrCriteria.ai_flags = AI_PASSIVE; // Accept on any address/port addrCriteria.ai_socktype = SOCK_DGRAM; // only datagram socket addrCriteria.ai_protocol = IPPROTO_UDP; // only UDP socket returnValue = getaddrinfo(NULL, serverPortString, &addrCriteria, &serverAddr); if(returnValue != 0) { fprintf(stderr, "getaddrinfo() failed.\n"); ExitWithMessage(returnValue, gai_strerror(returnValue)); } // Create socket for incomming connections socketHandle = socket(serverAddr->ai_family, serverAddr->ai_socktype, serverAddr->ai_protocol); if(socketHandle < 0) { fprintf(stderr, "socket() failed.\n"); ExitWithMessage(socketHandle, gai_strerror(socketHandle)); } // Bind to local address returnValue = bind(socketHandle, serverAddr->ai_addr, serverAddr->ai_addrlen); if(returnValue < 0) { fprintf(stderr, "bind() failed.\n"); ExitWithMessage(returnValue, gai_strerror(returnValue)); } // Free address list allocated by getaddrinfo freeaddrinfo(serverAddr); printf("Starting the UDP Server ...\n"); printf("Listinning at port %s\n\n", serverPortString); while(1) { receivedBytesCount = recvfrom( socketHandle, buffer, BUFFER_LENGTH, 0, (struct sockaddr *)&clientAddr, &clientAddrLen); // printf("Received %d bytes.\n", receivedBytesCount); if(receivedBytesCount < 0) { fprintf(stderr, "recvfrom() failed.\n"); ExitWithMessage(receivedBytesCount, gai_strerror(receivedBytesCount)); } fputs("Handling client ", stdout); PrintSocketAddress((struct sockaddr *)&clientAddr, stdout); fputs(" at ", stdout); PrintTime(stdout); fputc('\n', stdout); buffer[receivedBytesCount] = '\0'; fputs("Message: ", stdout); fputs(buffer, stdout); fputs("\n\n", stdout); ReverseMessage(buffer, receivedBytesCount); sendBytesCount = sendto(socketHandle, buffer, receivedBytesCount, 0, (struct sockaddr *)&clientAddr, sizeof(clientAddr)); if(sendBytesCount < 0) { fprintf(stderr, "sendto() failed.\n"); ExitWithMessage(sendBytesCount, gai_strerror(sendBytesCount)); } } return 0; } void ReverseMessage(char buffer[], ssize_t receivedBytesCount) { ssize_t i; ssize_t j; char temp; for(i = 0; i < receivedBytesCount / 2; i++) { j = receivedBytesCount - 1 - i; temp = buffer[i]; buffer[i] = buffer[j]; buffer[j] = temp; } } 
'; fputs("Message: ", stdout); fputs(buffer, stdout); fputs("\n\n", stdout); ReverseMessage(buffer, receivedBytesCount); sendBytesCount = sendto(socketHandle, buffer, receivedBytesCount, 0, (struct sockaddr *)&clientAddr, sizeof(clientAddr)); if(sendBytesCount < 0) { fprintf(stderr, "sendto() failed.\n"); ExitWithMessage(sendBytesCount, gai_strerror(sendBytesCount)); } } return 0; } void ReverseMessage(char buffer[], ssize_t receivedBytesCount) { ssize_t i; ssize_t j; char temp; for(i = 0; i < receivedBytesCount / 2; i++) { j = receivedBytesCount - 1 - i; temp = buffer[i]; buffer[i] = buffer[j]; buffer[j] = temp; } }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/118827.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • 九种边缘检测算法_边缘检测和边缘提取

    九种边缘检测算法_边缘检测和边缘提取0.绪论图像边缘是图像的重要特征,是图像中特性(如像素灰度、纹理等)分布的不连续处,图像周围特性有阶跃变化或屋脊状变化的那些像素集合。图像的边缘部分集中了图像的大部分信息,一幅图像的边缘结构与特点往往是决定图像特质的重要部分。图像边缘的另一个定义是指其周围像素灰度变化不连续的那些像素的集合。边缘广泛存在于物体与背景之间、物体与物体之间,因此,边缘是图像分割、图像理解及图像识别的重要特征。图像边缘检测主要用于增强图像中的轮廓边缘、细节以及灰度跳变部分,形成完整的物体边界,达到将物体从图像中分离出来或将表

    2022年10月28日
  • java抛出异常和捕获异常_java.lang.assertionerror

    java抛出异常和捕获异常_java.lang.assertionerror我有一个代码是围绕Web服务的Java包装程序,在例外情况下,它引发AxisFault异常(如下所示)org.apache.axis2.AxisFault:Policyenforcementfailedtoauthenticatetherequest.atorg.apache.axis2.util.Utils.getInboundFaultFromMessageContext(Ut…

  • Java IO流自动关闭

    Java IO流自动关闭Filef=newFile();Filedes=newFile();try(FileInputStreaminput=newFileInputStream(f);FileOutputStreamout=newFileOutputStream(des);){}catch(FileNotFoundExceptione1){ }catch(IO…

  • TIA PORTAL_Tia v17

    TIA PORTAL_Tia v17Coprocessor

  • SNMP MIB解析

    SNMP MIB解析

  • nginx系列之一:nginx入门

    nginx系列之一:nginx入门一、nginx功能介绍Nginx因为它的稳定性、丰富的模块库、灵活的配置和低系统资源的消耗而闻名.业界一致认为它是Apache2.2+mod_proxy_balancer的轻量级代替者,不仅是因为响应静态页面的速度非常快,而且它的模块数量达到Apache的近2/3。对proxy和rewrite模块的支持很彻底,还支持mod_fcgi、ssl、vhosts,适合用来做mongrelclust…

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号