UNIX網路程式設計學習(18)--UDP回射(伺服器+客戶端)程式

pengfoo發表於2012-05-10

伺服器端:

 

#include	"unp.h"

int
main(int argc, char **argv)
{
	int					sockfd;

	struct sockaddr_in	cliaddr, servaddr;

	sockfd = Socket(AF_INET, SOCK_DGRAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family      = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port        = htons(SERV_PORT);

	Bind(sockfd, (SA *) &servaddr, sizeof(servaddr));

    dg_echo(sockfd,(SA* ) &cliaddr, sizeof(cliaddr));

}

#include	"unp.h"

void
dg_echo(int sockfd ,SA *pcliaddr,socklen_t clilen)
{
    int     n;
    socklen_t   len;
    char    mesg[MAXLINE];

    for( ; ;)
    {
        len = clilen;
        n = Recvfrom(sockfd, mesg, MAXLINE ,0 ,pcliaddr,&len);
        Sendto(sockfd,mesg,n, 0, pcliaddr ,len);
    }
}


客戶端:

#include "unp.h"
#define DEST_IP "127.0.0.1"

int
main(int argc, char ** argv)
{
    int         sockfd;

    struct      sockaddr_in servaddr;

    sockfd = Socket(AF_INET, SOCK_DGRAM, 0);

    bzero(&servaddr, sizeof(struct sockaddr_in));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(SERV_PORT);

    Inet_pton(AF_INET, DEST_IP, &servaddr.sin_addr);

    dg_cli(stdin, sockfd, (SA *) &servaddr ,sizeof(servaddr));
    exit(0);
}

#include "unp.h"

void
dg_cli(FILE *fp, int sockfd, const SA* pservaddr, socklen_t servlen)
{
    int     n;
    char    sendline[MAXLINE], recvline[MAXLINE+1];
    while(Fgets(sendline, MAXLINE, fp) != NULL)
    {
        Sendto(sockfd, sendline, strlen(sendline), 0 , pservaddr, servlen);

        n = Recvfrom(sockfd ,recvline, MAXLINE, 0, NULL, NULL);

        recvline[n] = 0;

        Fputs(recvline, stdout);
    }
}


知道客戶端臨時埠號的任何程式都可以往客戶傳送資料包,這些資料包會與正常的伺服器應答混雜。解決方法是修改recvfrom呼叫以返回資料包傳送者的IP地址和埠號,保留來自資料包所發往伺服器的應答,而忽略任何其他資料包。

#include "unp.h"

void
dg_cli(FILE *fp, int sockfd, const SA* pservaddr, socklen_t servlen)
{
    int     n;
    char    sendline[MAXLINE], recvline[MAXLINE+1];
    socklen_t   len;
    struct sockaddr *preply_addr;
    preply_addr = Malloc(servlen);

    while(Fgets(sendline, MAXLINE, fp) != NULL)
    {
        Sendto(sockfd, sendline, strlen(sendline), 0 , pservaddr, servlen);

        len  = servlen;

        n = Recvfrom(sockfd ,recvline, MAXLINE, 0, preply_addr, &len);

        if(len != servlen || memcmp(pservaddr, preply_addr, len) != 0)
        {
            printf("reply from %s (ignored)\n", Sock_ntop(preply_addr, len));
            continue;
        }

        recvline[n] = 0;

        Fputs(recvline, stdout);
    }
    free(preply_addr);
}




 

相關文章