Mbed OS 文档翻译 之 参考(API(网络套接字(SocketAddress)))

SocketAddress

使用 SocketAddress 类表示唯一网络端点的 IP 地址和端口对。大多数网络函数也被重载以接受 IP 地址的字符串表示,但是您可以使用 SocketAddress 来避免在重复的网络事务期间解析 IP 地址的开销,并且您可以将其作为第一类对象传递。

SocketAddress 类参考

SocketAddress 类参考

公共成员函数
template
  SocketAddress (S *stack, const char *host, uint16_t port=0)
  SocketAddress (nsapi_addr_t addr=nsapi_addr_t(), uint16_t port=0)
  SocketAddress (const char *addr, uint16_t port=0)
  SocketAddress (const void *bytes, nsapi_version_t version, uint16_t port=0)
  SocketAddress (const SocketAddress &addr)
  ~SocketAddress ()
bool  set_ip_address (const char *addr)
void  set_ip_bytes (const void *bytes, nsapi_version_t version)
void  set_addr (nsapi_addr_t addr)
void  set_port (uint16_t port)
const char *  get_ip_address () const
const void *  get_ip_bytes () const
nsapi_version_t  get_ip_version () const
nsapi_addr_t  get_addr () const
uint16_t  get_port () const
  operator bool () const
SocketAddress &  operator= (const SocketAddress &addr)
友元
bool  operator== (const SocketAddress &a, const SocketAddress &b)
bool  operator!= (const SocketAddress &a, const SocketAddress &b)

SocketAddress 示例

以下是读取当前 UTC 时间的示例。此示例使用 SocketAddress 类获取服务器 IP 地址和端口。

main.cpp                                                                                                                                               导入到 Mbed IDE

#include "mbed.h"
#include "EthernetInterface.h"
 
// Network interface
EthernetInterface net;
 
// Time protocol implementation : Address: time.nist.gov UDPPort: 37  
 
typedef struct {
    uint32_t secs;         // Transmit Time-stamp seconds.
}ntp_packet;
 
int main() {
    // Bring up the ethernet interface
    printf("UDP Socket example\n");
    if(0 != net.connect()) {
        printf("Error connecting\n");
        return -1;
    }
 
    // Show the network address
    const char *ip = net.get_ip_address();
    printf("IP address is: %s\n", ip ? ip : "No IP");
        
    UDPSocket sock(&net);
    SocketAddress sockAddr;
 
    char out_buffer[] = "time";
    if(0 > sock.sendto("time.nist.gov", 37, out_buffer, sizeof(out_buffer))) {
        printf("Error sending data\n");
        return -1;
    }
    
    ntp_packet in_data;
    int n = sock.recvfrom(&sockAddr, &in_data, sizeof(ntp_packet));
    in_data.secs = ntohl( in_data.secs ) - 2208988800;    // 1900-1970
    printf("Time Received %lu seconds since 1/01/1900 00:00 GMT\n", 
                        (uint32_t)in_data.secs);
    printf("Time = %s", ctime(( const time_t* )&in_data.secs));
    
    printf("Time Server Address: %s Port: %d\n\r", 
                               sockAddr.get_ip_address(), sockAddr.get_port());
    
    // Close the socket and bring down the network interface
    sock.close();
    net.disconnect();
    return 0;
}
  • IP 网络架构。

你可能感兴趣的:(Mbed,OS,Mbed,Mbed,OS,Mbed,OS,5)