1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.channel.unix.tests;
17
18 import io.netty.channel.unix.DomainSocketAddress;
19 import io.netty.util.internal.PlatformDependent;
20
21 import java.io.File;
22 import java.io.IOException;
23 import java.lang.reflect.Method;
24 import java.net.InetAddress;
25 import java.net.InetSocketAddress;
26 import java.net.SocketAddress;
27
28 import static org.junit.jupiter.api.Assumptions.assumeTrue;
29
30 public final class UnixTestUtils {
31 private static final Object INET_LOOPBACK_UNAVAILABLE = new Object();
32 private static volatile Object inetLoopbackCache;
33
34
35
36
37 @Deprecated
38 public static DomainSocketAddress newSocketAddress() {
39 return newDomainSocketAddress();
40 }
41
42 public static DomainSocketAddress newDomainSocketAddress() {
43 try {
44 File file;
45 do {
46 file = PlatformDependent.createTempFile("NETTY", "UDS", null);
47 if (!file.delete()) {
48 throw new IOException("failed to delete: " + file);
49 }
50 } while (file.getAbsolutePath().length() > 128);
51 return new DomainSocketAddress(file);
52 } catch (IOException e) {
53 throw new IllegalStateException(e);
54 }
55 }
56
57
58
59
60
61
62 public static SocketAddress newInetLoopbackSocketAddress() {
63 Object loopback = inetLoopbackCache;
64
65 if (loopback == null) {
66 inetLoopbackCache = loopback = getLoopbackAddress();
67 }
68
69 assumeTrue(loopback != INET_LOOPBACK_UNAVAILABLE, "InetAddress.getLoopbackAddress() is not available");
70 return new InetSocketAddress((InetAddress) loopback, 0);
71 }
72
73 private static Object getLoopbackAddress() {
74 try {
75 Method method = InetAddress.class.getMethod("getLoopbackAddress");
76 return method.invoke(null);
77 } catch (Exception ignore) {
78 return INET_LOOPBACK_UNAVAILABLE;
79 }
80 }
81
82 private UnixTestUtils() { }
83 }