-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmyip
More file actions
executable file
·40 lines (32 loc) · 1020 Bytes
/
Copy pathmyip
File metadata and controls
executable file
·40 lines (32 loc) · 1020 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/env python3
"""Print your local network IP V4 address and write it to the system clipboard.
Usage:
myip
author: andreasl
"""
import os
import shutil
import socket
import subprocess
# Ask the kernel which source address it would pick to reach the outside world.
# Connecting a UDP socket sends no packets; it only performs a route lookup.
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.connect(("1.1.1.1", 53))
ip_addr = sock.getsockname()[0]
print(ip_addr)
if shutil.which("pbcopy"):
clip_cmd = ["pbcopy"]
elif shutil.which("xclip") and os.environ.get("DISPLAY"):
clip_cmd = ["xclip", "-selection", "clipboard"]
else:
msg = "No clipboard application set!"
raise RuntimeError(msg)
# Set stdout to DEVNULL in order to keep `xclip`, which forks and keeps running to
# own the selection, from holding our stdout open and making the script hang.
subprocess.run(
clip_cmd,
input=ip_addr,
text=True,
check=True,
stdout=subprocess.DEVNULL,
)