作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
以下是一个非常简单的ruby服务器。
require 'socket'
local_socket = Socket.new(:INET, :STREAM)
local_addr = Socket.pack_sockaddr_in(4481, '0.0.0.0')
local_socket.bind(local_addr)
local_socket.listen(Socket::SOMAXCONN)
# accept a connection
connection, remote_addr = local_socket.accept
> connection.instance_variables
[]
> p connection.local_address
Local address: #<Addrinfo: 0.0.0.0:4481 TCP>
> p connection.remote_address
Remote address #<Addrinfo: 59.102.12.1:4481 TCP>
最佳答案
#local_address
和 #remote_address
分别使用 getsockname
和 getpeername
。
从Ruby source code, ext/socket/basicsocket.c
:
static VALUE
bsock_local_address(VALUE sock)
{
union_sockaddr buf;
socklen_t len = (socklen_t)sizeof buf;
socklen_t len0 = len;
rb_io_t *fptr;
GetOpenFile(sock, fptr);
if (getsockname(fptr->fd, &buf.addr, &len) < 0)
rb_sys_fail("getsockname(2)");
if (len0 < len) len = len0;
return rsock_fd_socket_addrinfo(fptr->fd, &buf.addr, len);
}
static VALUE
bsock_remote_address(VALUE sock)
{
union_sockaddr buf;
socklen_t len = (socklen_t)sizeof buf;
socklen_t len0 = len;
rb_io_t *fptr;
GetOpenFile(sock, fptr);
if (getpeername(fptr->fd, &buf.addr, &len) < 0)
rb_sys_fail("getpeername(2)");
if (len0 < len) len = len0;
return rsock_fd_socket_addrinfo(fptr->fd, &buf.addr, len);
}
关于ruby - Ruby:Ruby Socket对象中的remote_address/local_address存放在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31846160/
我是一名优秀的程序员,十分优秀!