本文整理汇总了Java中java.net.Socket.getRemoteSocketAddress方法的典型用法代码示例。如果您正苦于以下问题:Java Socket.getRemoteSocketAddress方法的具体用法?Java Socket.getRemoteSocketAddress怎么用?Java Socket.getRemoteSocketAddress使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.net.Socket
的用法示例。
在下文中一共展示了Socket.getRemoteSocketAddress方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: toString
import java.net.Socket; //导入方法依赖的package包/类
@Override
public String toString() {
final Socket socket = this.socketHolder.get();
if (socket != null) {
final StringBuilder buffer = new StringBuilder();
final SocketAddress remoteAddress = socket.getRemoteSocketAddress();
final SocketAddress localAddress = socket.getLocalSocketAddress();
if (remoteAddress != null && localAddress != null) {
NetUtils.formatAddress(buffer, localAddress);
buffer.append("<->");
NetUtils.formatAddress(buffer, remoteAddress);
}
return buffer.toString();
} else {
return "[Not bound]";
}
}
示例2: LearnerHandler
import java.net.Socket; //导入方法依赖的package包/类
LearnerHandler(Socket sock, BufferedInputStream bufferedInput,
Leader leader) throws IOException {
super("LearnerHandler-" + sock.getRemoteSocketAddress());
this.sock = sock;
this.leader = leader;
this.bufferedInput = bufferedInput;
try {
leader.self.authServer.authenticate(sock,
new DataInputStream(bufferedInput));
} catch (IOException e) {
LOG.error("Server failed to authenticate quorum learner, addr: {}, closing connection",
sock.getRemoteSocketAddress(), e);
try {
sock.close();
} catch (IOException ie) {
LOG.error("Exception while closing socket", ie);
}
throw new SaslException("Authentication failure: " + e.getMessage());
}
}
示例3: run
import java.net.Socket; //导入方法依赖的package包/类
/**
* Forwarder main loop
*/
@Override
public void run() {
try {
// Loop on incoming connections
while(true) {
// Accept
final Socket socket = mServerSocket.accept();
if(socket == null) break;
InetSocketAddress localAddr = (InetSocketAddress)socket.getRemoteSocketAddress();
if(!localAddr.getAddress().isLoopbackAddress())
continue;
// Spawn a thread
Thread t = new Thread() {
@Override
public void run() {
handle(socket);
}
};
t.start();
}
}
catch(IOException e) {
e.printStackTrace();
}
}
示例4: readMessage
import java.net.Socket; //导入方法依赖的package包/类
private void readMessage(MockChannel mockChannel, StreamInput input) throws IOException {
Socket socket = mockChannel.activeChannel;
byte[] minimalHeader = new byte[TcpHeader.MARKER_BYTES_SIZE];
int firstByte = input.read();
if (firstByte == -1) {
throw new IOException("Connection reset by peer");
}
minimalHeader[0] = (byte) firstByte;
minimalHeader[1] = (byte) input.read();
int msgSize = input.readInt();
if (msgSize == -1) {
socket.getOutputStream().flush();
} else {
BytesStreamOutput output = new BytesStreamOutput();
final byte[] buffer = new byte[msgSize];
input.readFully(buffer);
output.write(minimalHeader);
output.writeInt(msgSize);
output.write(buffer);
final BytesReference bytes = output.bytes();
if (TcpTransport.validateMessageHeader(bytes)) {
InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
messageReceived(bytes.slice(TcpHeader.MARKER_BYTES_SIZE + TcpHeader.MESSAGE_LENGTH_SIZE, msgSize),
mockChannel, mockChannel.profile, remoteAddress, msgSize);
} else {
// ping message - we just drop all stuff
}
}
}
示例5: getRemoteAddress
import java.net.Socket; //导入方法依赖的package包/类
/**
* {@inheritDoc}
*/
public InetSocketAddress getRemoteAddress() {
if (channel == null) {
return null;
}
Socket socket = getSocket();
if (socket == null) {
return null;
}
return (InetSocketAddress) socket.getRemoteSocketAddress();
}
示例6: checkAuthStatus
import java.net.Socket; //导入方法依赖的package包/类
private void checkAuthStatus(Socket sock, QuorumAuth.Status qpStatus)
throws SaslException {
if (qpStatus == QuorumAuth.Status.SUCCESS) {
LOG.info("Successfully completed the authentication using SASL. server addr: {}, status: {}",
sock.getRemoteSocketAddress(), qpStatus);
} else {
throw new SaslException("Authentication failed against server addr: "
+ sock.getRemoteSocketAddress() + ", qpStatus: "
+ qpStatus);
}
}
示例7: DataSocket
import java.net.Socket; //导入方法依赖的package包/类
/**
* Instantiates the wrapper object based on an existing {@link Socket}
* @throws DataSocketFailedToInitialiseException If the socket provided is <code>null</code> or if there
* is any error when attempting to create the {@link DataInputStream} or {@link DataOutputStream}.
* @see #initialiseIOStreams()
*/
public DataSocket(Socket socket) throws DataSocketFailedToInitialiseException {
if(socket == null)
throw new DataSocketFailedToInitialiseException(new NullPointerException("socket"));
this.socket = socket;
this.remoteSocketAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
initialiseIOStreams();
log.info("New connection on socket: {}", remoteSocketAddress);
}
示例8: wrapXmppTalk
import java.net.Socket; //导入方法依赖的package包/类
public static void wrapXmppTalk(OpenFireTalk xmppTalk) {
try {
Socket socket = xmppTalk.getSocket();
SSLContext sslContext = getSslContext();
InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
SSLSocketFactory sf = sslContext.getSocketFactory();
SSLSocket s = (SSLSocket) (sf.createSocket(socket, remoteAddress.getHostName(), socket.getPort(), true));
s.setUseClientMode(true);
s.startHandshake();
xmppTalk.setSocket(s);
} catch (Exception e) {
e.printStackTrace();
}
}
示例9: LearnerHandler
import java.net.Socket; //导入方法依赖的package包/类
LearnerHandler(Socket sock, Leader leader) throws IOException {
super("LearnerHandler-" + sock.getRemoteSocketAddress());
this.sock = sock;
this.leader = leader;
leader.addLearnerHandler(this);
}
示例10: updateSocketAddresses
import java.net.Socket; //导入方法依赖的package包/类
private void updateSocketAddresses() {
Socket socket = ((SocketChannel) sockKey.channel()).socket();
localSocketAddress = socket.getLocalSocketAddress();
remoteSocketAddress = socket.getRemoteSocketAddress();
}
示例11: readClientVersion
import java.net.Socket; //导入方法依赖的package包/类
private static Version readClientVersion(ServerConnection connection)
throws IOException, VersionException {
Socket socket = connection.getSocket();
int timeout = connection.getHandShakeTimeout();
int soTimeout = -1;
try {
soTimeout = socket.getSoTimeout();
socket.setSoTimeout(timeout);
InputStream is = socket.getInputStream();
short clientVersionOrdinal = Version.readOrdinalFromInputStream(is);
if (clientVersionOrdinal == -1) {
throw new EOFException(
LocalizedStrings.ServerHandShakeProcessor_HANDSHAKEREADER_EOF_REACHED_BEFORE_CLIENT_VERSION_COULD_BE_READ
.toLocalizedString());
}
Version clientVersion = null;
try {
clientVersion = Version.fromOrdinal(clientVersionOrdinal, true);
} catch (UnsupportedVersionException uve) {
// Allows higher version of wan site to connect to server
if (connection.getCommunicationMode() == Acceptor.GATEWAY_TO_GATEWAY
&& !(clientVersionOrdinal == Version.NOT_SUPPORTED_ORDINAL)) {
return Acceptor.VERSION;
} else {
SocketAddress sa = socket.getRemoteSocketAddress();
String sInfo = "";
if (sa != null) {
sInfo = " Client: " + sa.toString() + ".";
}
throw new UnsupportedVersionException(uve.getMessage() + sInfo);
}
}
if (!clientVersion.compatibleWith(Acceptor.VERSION)) {
throw new IncompatibleVersionException(clientVersion, Acceptor.VERSION);// we can throw this
// to restrict
} // Backward Compatibilty Support to limited no of versions
return clientVersion;
} finally {
if (soTimeout != -1) {
try {
socket.setSoTimeout(soTimeout);
} catch (IOException ignore) {
}
}
}
}
示例12: main
import java.net.Socket; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
String extension = args[0];
String targetHost = args[1];
// enable CRLDP and AIA extensions
System.setProperty("com.sun.security.enableCRLDP", "true");
System.setProperty("com.sun.security.enableAIAcaIssuers", "true");
Path hostsFilePath = Paths.get(System.getProperty("test.src", ".")
+ File.separator + extension);
System.setProperty("jdk.net.hosts.file",
hostsFilePath.toFile().getAbsolutePath());
X509Certificate trustedCert = loadCertificate(CA_CERT);
X509Certificate eeCert = loadCertificate(EE_CERT);
Set<TrustAnchor> trustedCertsSet = new HashSet<>();
trustedCertsSet.add(new TrustAnchor(trustedCert, null));
CertPath cp = (CertPath) CertificateFactory.getInstance("X509")
.generateCertPath(Arrays.asList(eeCert));
// CertPath validator should try to parse CRLDP and AIA extensions,
// and load CRLs/certs which they point to.
// If proxy server catches requests for resolving host names
// which extensions contain, then it means that CertPath validator
// tried to load CRLs/certs which they point to.
List<String> hosts = new ArrayList<>();
Consumer<Socket> socketConsumer = (Socket socket) -> {
InetSocketAddress remoteAddress
= (InetSocketAddress) socket.getRemoteSocketAddress();
hosts.add(remoteAddress.getHostName());
};
try (SocksProxy proxy = SocksProxy.startProxy(socketConsumer)) {
CertPathValidator.getInstance("PKIX").validate(cp,
new PKIXParameters(trustedCertsSet));
throw new RuntimeException("CertPathValidatorException not thrown");
} catch (CertPathValidatorException cpve) {
System.out.println("Expected exception: " + cpve);
}
if (!hosts.contains(targetHost)) {
throw new RuntimeException(
String.format("The %s from %s extension is not requested",
targetHost, extension));
}
System.out.println("Test passed");
}
示例13: run
import java.net.Socket; //导入方法依赖的package包/类
/**
* start up the server socket and when a new connection is received, check that
* the source address is in our permitted list and if so, start a new console input
* on that socket.
*/
@Override
public void run()
{
int threadNum = 1;
System.out.println("Telnet server started. Listening on port: " + serverSocket.getLocalPort());
while( true ) {
try {
Socket socket = serverSocket.accept();
InetSocketAddress addr = (InetSocketAddress) socket.getRemoteSocketAddress();
if( addr.isUnresolved() || ! isAllowed(addr) ) {
System.out.println("TelnetUI: rejecting connection from: " + addr + " as address is not allowed");
socket.close();
}
else {
System.out.println("TelnetUI: accepting connection from: " + addr);
int loginAttempts = 0;
while( true ) {
// TODO: might want to put this in another thread so the port doesnt block while the user logs in
//System.out.println("TelnetUI: starting login" );
UserProfile profile = login( socket.getInputStream(), socket.getOutputStream() );
//System.out.println("TelnetUI: login profile obtained" );
if( profile != null ) {
//System.out.println("TelnetUI: creating console input" );
ui.createNewConsoleInput("Telnet Console " + threadNum++, socket.getInputStream(), new PrintStream(socket.getOutputStream()), profile);
break;
}
//System.out.println("TelnetUI: failed to obtain login profile" );
loginAttempts++;
if( loginAttempts >= maxLoginAttempts ) {
System.out.println("TelnetUI: rejecting connection from: " + addr + " as number of failed connections > max login attempts (" + maxLoginAttempts + ")");
socket.close();
break;
}
}
}
}
catch (Throwable t) {
t.printStackTrace();
break;
}
}
}
示例14: QuorumConnectionReceiverThread
import java.net.Socket; //导入方法依赖的package包/类
QuorumConnectionReceiverThread(final Socket sock) {
super("QuorumConnectionReceiverThread-" + sock.getRemoteSocketAddress());
this.sock = sock;
}
示例15: authenticate
import java.net.Socket; //导入方法依赖的package包/类
@Override
public void authenticate(Socket sock, String hostName) throws IOException {
if (!quorumRequireSasl) { // let it through, we don't require auth
LOG.info("Skipping SASL authentication as {}={}",
QuorumAuth.QUORUM_LEARNER_SASL_AUTH_REQUIRED,
quorumRequireSasl);
return;
}
SaslClient sc = null;
String principalConfig = SecurityUtils
.getServerPrincipal(quorumServicePrincipal, hostName);
try {
DataOutputStream dout = new DataOutputStream(
sock.getOutputStream());
DataInputStream din = new DataInputStream(sock.getInputStream());
byte[] responseToken = new byte[0];
sc = SecurityUtils.createSaslClient(learnerLogin.getSubject(),
principalConfig,
QuorumAuth.QUORUM_SERVER_PROTOCOL_NAME,
QuorumAuth.QUORUM_SERVER_SASL_DIGEST, LOG, "QuorumLearner");
if (sc.hasInitialResponse()) {
responseToken = createSaslToken(new byte[0], sc, learnerLogin);
}
send(dout, responseToken);
QuorumAuthPacket authPacket = receive(din);
QuorumAuth.Status qpStatus = QuorumAuth.Status
.getStatus(authPacket.getStatus());
while (!sc.isComplete()) {
switch (qpStatus) {
case SUCCESS:
responseToken = createSaslToken(authPacket.getToken(), sc,
learnerLogin);
// we're done; don't expect to send another BIND
if (responseToken != null) {
throw new SaslException(
"Protocol error: attempting to send response after completion"
+ ". Server addr: "
+ sock.getRemoteSocketAddress());
}
break;
case IN_PROGRESS:
responseToken = createSaslToken(authPacket.getToken(), sc,
learnerLogin);
send(dout, responseToken);
authPacket = receive(din);
qpStatus = QuorumAuth.Status
.getStatus(authPacket.getStatus());
break;
case ERROR:
throw new SaslException(
"Authentication failed against server addr: "
+ sock.getRemoteSocketAddress());
default:
LOG.warn("Unknown status:{}!", qpStatus);
throw new SaslException(
"Authentication failed against server addr: "
+ sock.getRemoteSocketAddress());
}
}
// Validate status code at the end of authentication exchange.
checkAuthStatus(sock, qpStatus);
} finally {
if (sc != null) {
try {
sc.dispose();
} catch (SaslException e) {
LOG.error("SaslClient dispose() failed", e);
}
}
}
return;
}