网络序和字节序转换源码

1 #define HTONL(n) (((((unsigned long)(n) & 0xFF)) << 24) |  ((((unsigned long)(n) & 0xFF00)) << 8) | ((((unsigned long)(n) & 0xFF0000)) >> 8) | ((((unsigned long)(n) & 0xFF000000)) >> 24))
2 #define HTONS(n) (((unsigned short(n) & 0xFF)) << 8)) |(((unsigned short(n) & 0xFF00) >> 8))
#pragma comment(lib,"ws2_32.lib")
#include <stdio.h>
#include <winsock2.h>
#include <iostream>
using namespace std;
#define HTONL(n) (((((unsigned long)(n) & 0xFF)) << 24) |  ((((unsigned long)(n) & 0xFF00)) << 8) | ((((unsigned long)(n) & 0xFF0000)) >> 8) | ((((unsigned long)(n) & 0xFF000000)) >> 24))
#define HTONS(n) (((unsigned short(n) & 0xFF)) << 8)) |(((unsigned short(n) & 0xFF00) >> 8))


void ErrorHandling(char* message)
{
    fputs(message,stderr);
    fputc('\n',stderr);
    exit(1);
}
int main()
{
    WSADATA wsaData;    //定义库
    unsigned short host_port = 0x1234;
    unsigned short net_port;
    unsigned long host_addr = 0x12345678;
    unsigned long net_addr;
    if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0); //库初始化
        //ErrorHandling("WSAStartup() error!");

    net_port = htons(host_port); //转换为网络字节序
    net_addr = htonl(host_addr);

    printf("Host ordered port: %#x \n", host_port);
    printf("Network ordered port: %#x \n", net_port);
    printf("Host ordered address: %#lx \n", host_addr);
    printf("Network ordered address: %#lx \n", net_addr);
    WSACleanup();//关闭库
    system("pause");
    return 0;
}

 

posted @ 2019-10-14 11:21  冷眼旁观你的泪  阅读(328)  评论(0编辑  收藏  举报